Skip to content
This repository has been archived by the owner on Apr 25, 2024. It is now read-only.

feat: Add support to allow alternate WebAPI Fetch implementation #50

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 63 additions & 5 deletions lib/Resource.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ Resource.prototype = {
);
}
},

_get_headers: function(requestData) {
var apiVersion = this._shippo.get('version');
var headers = {
Expand All @@ -178,8 +179,42 @@ Resource.prototype = {
return headers

},
_request: function(method, path, data, auth, callback) {

_formFetchResponse(response) {
return new Promise(resolve => {
response.text().then(body => {
let json = '{}'

if (body !== '') {
json = JSON.parse(body)
}

if (!response.ok) {
json = { errors: [{ status: response.status }] }
}

resolve({
status: response.status,
ok: response.ok,
json
})
})
})
},

_handleFetchResponse(response) {
var self = this;

return self._formFetchResponse(response).then(responseObj => {
if(responseObj.ok) {
return responseObj.json;
} else {
throw new Error(responseObj.json);
}
}).catch(error => reject(error));
},

_request: function(method, path, data, auth, callback) {
var requestData = new Buffer(JSON.stringify(data || {}));
var self = this;
var queryParams = querystring.stringify(data);
Expand All @@ -188,8 +223,33 @@ Resource.prototype = {
path = [path, queryParams].join('?');
}

var headers = self._get_headers(requestData)
makeRequest();
const headers = self._get_headers(requestData);
const Fetch = self._shippo.get('Fetch');
if(Fetch && typeof(Fetch) === 'function') {
var uri = (self._shippo.get('endpoint'))?self._shippo.get('endpoint'):`${self._shippo.get('protocol') == 'http' ? 'http' : 'https'}://${self._shippo.get('host')}:${self._shippo.get('port')||80}${path}`;

Fetch.bind(self)(new Request(uri, {
method: method,
body: JSON.stringify(data),
headers: new Headers(headers)
}))
.then(fetchResponse => self._handleFetchResponse(fetchResponse))
.then(response => {
return callback.call(self, null, response);
})
.catch(error => {
return callback.call(
self,
new Error.ShippoConnectionError({
message: 'An error occurred with our connection to Shippo',
detail: error
}),
null
);
});
} else {
makeRequest();
}

function makeRequest() {

Expand All @@ -211,9 +271,7 @@ Resource.prototype = {

req.write(requestData);
req.end();

}

}

};
Expand Down
20 changes: 16 additions & 4 deletions lib/shippo.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ Shippo.DEFAULT_HOST = 'api.goshippo.com';
Shippo.DEFAULT_PROTOCOL = 'https';
Shippo.DEFAULT_PORT = '443';
Shippo.DEFAULT_BASE_PATH = '/';
Shippo.DEFAULT_TIMEOUT = require('http').createServer().timeout;
Shippo.DEFAULT_TIMEOUT = 2000;
try{
// http is not in package.json so this fails unless installed
Shippo.DEFAULT_TIMEOUT = require('http').createServer().timeout;
}catch(error){}

//require('../package.json').version;
Shippo.PACKAGE_VERSION = '0.0.2';

Expand All @@ -27,10 +32,9 @@ Shippo.resources = {

Shippo.Resource = require('./Resource');

function Shippo(token) {

function Shippo(token, params = null) {
if (!(this instanceof Shippo)) {
return new Shippo(token);
return new Shippo(token, params);
}


Expand All @@ -47,6 +51,14 @@ function Shippo(token) {
this.setToken(token);
}

if(params && Array.isArray(params)) {
Object.values(params).map((param) => {
Object.entries(param).map(([key, value]) => {
this.set(key, value);
});
});
}

this._init();
}

Expand Down