Skip to content

Commit

Permalink
Make SendGrid a factory that enables multiple prototype instances
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Kirkpatrick committed Aug 22, 2016
1 parent 439e173 commit d448eca
Showing 1 changed file with 42 additions and 37 deletions.
79 changes: 42 additions & 37 deletions lib/sendgrid.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,55 +64,60 @@ function makeHeaders(apiKey, globalHeaders) {
* 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
var globalRequest = getEmptyRequest({
this.globalRequest = getEmptyRequest({
host: host || 'api.sendgrid.com',
headers: makeHeaders(apiKey, globalHeaders),
});

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

//Interact with the API with this function
SendGrid.API = function(request, callback) {
//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) {
client.API(request, function(response) {
if (isValidResponse(response)) {
resolve(response);
}
else {
var error = new SendGridError('Response error');
error.response = response;
reject(error);
}
});
});
//If no callback provided, we will return a promise
if (!callback) {
if (!SendGrid.Promise) {
throw new SendGridError('Promise API not supported');
}

//Use callback
client.API(request, function(response) {
if (isValidResponse(response)) {
callback(null, response);
}
else {
var error = new SendGridError('Response error');
callback(error, response);
}
return new SendGrid.Promise(function(resolve, reject) {
self.client.API(request, function(response) {
if (isValidResponse(response)) {
resolve(response);
}
else {
var error = new SendGridError('Response error');
error.response = response;
reject(error);
}
});
});
};
}

//Set requests
SendGrid.emptyRequest = getEmptyRequest;
SendGrid.globalRequest = globalRequest;
return SendGrid;
}
//Use callback
self.client.API(request, function(response) {
if (isValidResponse(response)) {
callback(null, response);
}
else {
var error = new SendGridError('Response error');
callback(error, response);
}
});
};

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

//Try to use native promises by default
if (typeof Promise !== 'undefined') {
Expand Down

0 comments on commit d448eca

Please sign in to comment.