From d448ecae0ba4ce60733d4729ada035fddc794410 Mon Sep 17 00:00:00 2001 From: Tom Kirkpatrick Date: Mon, 22 Aug 2016 11:00:53 +0200 Subject: [PATCH] Make SendGrid a factory that enables multiple prototype instances --- lib/sendgrid.js | 79 ++++++++++++++++++++++++++----------------------- 1 file changed, 42 insertions(+), 37 deletions(-) diff --git a/lib/sendgrid.js b/lib/sendgrid.js index eb58f84df..6681d284f 100644 --- a/lib/sendgrid.js +++ b/lib/sendgrid.js @@ -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') {