-
Notifications
You must be signed in to change notification settings - Fork 780
/
Copy pathclient.js
189 lines (160 loc) · 4.81 KB
/
client.js
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
'use strict';
const axios = require('axios');
const pkg = require('../../package.json');
const {
helpers: {
mergeData,
},
classes: {
Response,
ResponseError,
},
} = require('@sendgrid/helpers');
const API_KEY_PREFIX = 'SG.';
const SENDGRID_BASE_URL = 'https://api.sendgrid.com/';
const TWILIO_BASE_URL = 'https://email.twilio.com/';
const SENDGRID_REGION = 'global';
// Initialize the allowed regions and their corresponding hosts
const REGION_HOST_MAP = {
eu: 'https://api.eu.sendgrid.com/',
global: 'https://api.sendgrid.com/',
};
class Client {
constructor() {
this.auth = '';
this.impersonateSubuser = '';
this.sendgrid_region = SENDGRID_REGION;
this.defaultHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'sendgrid/' + pkg.version + ';nodejs',
};
this.defaultRequest = {
baseUrl: SENDGRID_BASE_URL,
url: '',
method: 'GET',
headers: {},
maxContentLength: Infinity, // Don't limit the content length.
maxBodyLength: Infinity,
};
}
setApiKey(apiKey) {
this.auth = 'Bearer ' + apiKey;
this.setDefaultRequest('baseUrl', REGION_HOST_MAP[this.sendgrid_region]);
if (!this.isValidApiKey(apiKey)) {
console.warn(`API key does not start with "${API_KEY_PREFIX}".`);
}
}
setTwilioEmailAuth(username, password) {
const b64Auth = Buffer.from(username + ':' + password).toString('base64');
this.auth = 'Basic ' + b64Auth;
this.setDefaultRequest('baseUrl', TWILIO_BASE_URL);
if (!this.isValidTwilioAuth(username, password)) {
console.warn('Twilio Email credentials must be non-empty strings.');
}
}
isValidApiKey(apiKey) {
return this.isString(apiKey) && apiKey.trim().startsWith(API_KEY_PREFIX);
}
isValidTwilioAuth(username, password) {
return this.isString(username) && username
&& this.isString(password) && password;
}
isString(value) {
return typeof value === 'string' || value instanceof String;
}
setImpersonateSubuser(subuser) {
this.impersonateSubuser = subuser;
}
setDefaultHeader(key, value) {
if (key !== null && typeof key === 'object') {
// key is an object
Object.assign(this.defaultHeaders, key);
return this;
}
this.defaultHeaders[key] = value;
return this;
}
setDefaultRequest(key, value) {
if (key !== null && typeof key === 'object') {
// key is an object
Object.assign(this.defaultRequest, key);
return this;
}
this.defaultRequest[key] = value;
return this;
}
/**
* Global is the default residency (or region)
* Global region means the message will be sent through https://api.sendgrid.com
* EU region means the message will be sent through https://api.eu.sendgrid.com
**/
setDataResidency(region) {
if (!REGION_HOST_MAP.hasOwnProperty(region)) {
console.warn('Region can only be "global" or "eu".');
} else {
this.sendgrid_region = region;
this.setDefaultRequest('baseUrl', REGION_HOST_MAP[region]);
}
return this;
}
createHeaders(data) {
// Merge data with default headers.
const headers = mergeData(this.defaultHeaders, data);
// Add auth, but don't overwrite if header already set.
if (typeof headers.Authorization === 'undefined' && this.auth) {
headers.Authorization = this.auth;
}
if (this.impersonateSubuser) {
headers['On-Behalf-Of'] = this.impersonateSubuser;
}
return headers;
}
createRequest(data) {
let options = {
url: data.uri || data.url,
baseUrl: data.baseUrl,
method: data.method,
data: data.body,
params: data.qs,
headers: data.headers,
};
// Merge data with default request.
options = mergeData(this.defaultRequest, options);
options.headers = this.createHeaders(options.headers);
options.baseURL = options.baseUrl;
delete options.baseUrl;
return options;
}
request(data, cb) {
data = this.createRequest(data);
const promise = new Promise((resolve, reject) => {
axios(data)
.then(response => {
return resolve([
new Response(response.status, response.data, response.headers),
response.data,
]);
})
.catch(error => {
if (error.response) {
if (error.response.status >= 400) {
return reject(new ResponseError(error.response));
}
}
return reject(error);
});
});
// Throw an error in case a callback function was not passed.
if (cb && typeof cb !== 'function') {
throw new Error('Callback passed is not a function.');
}
if (cb) {
return promise
.then(result => cb(null, result))
.catch(error => cb(error, null));
}
return promise;
}
}
module.exports = Client;