summaryrefslogtreecommitdiffstats
path: root/lib/sendgrid.js
blob: c547e99648de2b4b03944d97117ab61a6d0491d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/* eslint dot-notation: 'off' */
'use strict';

/**
 * Dependencies
 */
var pkg = require('./../package.json');
var sendgridRest = require('sendgrid-rest');
var emptyRequest = sendgridRest.emptyRequest;
var Client = sendgridRest.Client;
var SendGridError = require('./helpers/error');

/**
 * Helper to check if response is valid
 */
function isValidResponse(response) {
  return (
    response &&
    response.statusCode &&
    response.statusCode >= 200 &&
    response.statusCode <= 299
  );
}

/**
 * Helper to get a new empty request
 */
function getEmptyRequest(data) {
  var request = JSON.parse(JSON.stringify(emptyRequest));
  if (data && typeof data === 'object') {
    for (var key in data) {
      if (data.hasOwnProperty(key)) {
        request[key] = JSON.parse(JSON.stringify(data[key]));
      }
    }
  }
  return request;
}

/**
 * Helper to make headers
 */
function makeHeaders(apiKey, globalHeaders) {
  var headers = {};
  headers['Authorization'] = 'Bearer '.concat(apiKey);
  headers['Accept'] = 'application/json';
  headers['User-Agent'] = 'sendgrid/' + pkg.version + ';nodejs';
  if (globalHeaders) {
    for (var obj in globalHeaders) {
      if (globalHeaders.hasOwnProperty(obj) &&
        typeof globalHeaders[obj] === 'object') {
        for (var key in globalHeaders[obj]) {
          if (globalHeaders[obj].hasOwnProperty(key)) {
            headers[key] = globalHeaders[obj][key];
          }
        }
      }
    }
  }
  return headers;
}

/**
 * SendGrid allows for quick and easy access to the v3 Web API
 */
function SendGrid(apiKey, host, globalHeaders) {
  return new SendGridInstance(apiKey, host, globalHeaders);
}

/**
 * SendGrid allows for quick and easy access to the v3 Web API
 */
function SendGridInstance(apiKey, host, globalHeaders) {
  //Create global request
  this.globalRequest = getEmptyRequest({
    host: host || 'api.sendgrid.com',
    headers: makeHeaders(apiKey, globalHeaders),
  });

  //Initialize new client
  this.client = new Client(this.globalRequest);
}

//Interact with the API with this function
SendGridInstance.prototype.API = function(request, callback) {
  var self = this;

  //If no callback provided, we will return a promise
  if (!callback) {
    if (!SendGrid.Promise) {
      throw new SendGridError('Promise API not supported');
    }
    return new SendGrid.Promise(function(resolve, reject) {
      self.client.API(request, function(response) {
        response.body = response.body ? JSON.parse(response.body) : response.body;
        if (isValidResponse(response)) {
          resolve(response);
        }
        else {
          var error = new SendGridError('Response error');
          error.response = response;
          reject(error);
        }
      });
    });
  }

  //Use callback
  self.client.API(request, function(response) {
    response.body = response.body ? JSON.parse(response.body) : response.body;
    if (isValidResponse(response)) {
      callback(null, response);
    }
    else {
      var error = new SendGridError('Response error');
      error.response = response;
      callback(error, response);
    }
  });
};

//Set requests
SendGridInstance.prototype.emptyRequest = getEmptyRequest;

//Try to use native promises by default
if (typeof Promise !== 'undefined') {
  SendGrid.Promise = Promise;
}
else {
  SendGrid.Promise = null;
}

//Export
module.exports = SendGrid;