UNPKG

cimpress-fulfiller-identity

Version:
238 lines (207 loc) 10.1 kB
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var axios = require('axios'); var axiosRetry = require('axios-retry'); var FulfillerNotFoundError = require("./errors/fulfiller_not_found_error"); var ForbiddenError = require("./errors/forbidden_error"); var XRayProxy = require("./xray_proxy"); var Fulfiller = require("./fulfiller"); var FulfillerContact = require("./fulfillerContact"); var AWSXRayMock = require('./aws_xray_mock'); /** * The main class exposing client methods. */ var FulfillerIdentityClient = function () { function FulfillerIdentityClient(authorization, clientOptions) { _classCallCheck(this, FulfillerIdentityClient); var options = clientOptions || {}; var awsXRay = options.AWSXRay ? options.AWSXRay : AWSXRayMock; var retries = parseInt(options.retries, 10); var retryDelayInMs = parseInt(options.retryDelayInMs, 10); var retryOnTimeouts = options.retryOnTimeouts || false; if (typeof authorization === "undefined") { this.authorizer = { getAuthorization: function getAuthorization() { return Promise.resolve(""); } }; } else if (typeof authorization === "string") { this.authorizer = { getAuthorization: function getAuthorization() { return Promise.resolve(authorization.startsWith('Bearer ') ? authorization : 'Bearer ' + authorization); } }; } else if (typeof authorization === "function") { this.authorizer = { getAuthorization: function getAuthorization() { return Promise.resolve(authorization()); } }; } else { throw new Error("The authorization should be either a string, a function that returns a string, or a function that returns a Promise"); } this.timeout = options.timeout ? options.timeout : 3000; this.baseUrl = options.url ? options.url : "https://fulfilleridentity.trdlnk.cimpress.io"; this.xrayPRoxy = new XRayProxy(this.authorizer, awsXRay); var retryCondition = retryOnTimeouts ? function (err) { return err.code === 'ECONNABORTED' || axiosRetry.isNetworkOrIdempotentRequestError(err); } : axiosRetry.isNetworkOrIdempotentRequestError; axiosRetry(axios, { retries: retries >= 0 ? retries : 3, retryDelay: function retryDelay(retryCount) { return retryDelayInMs >= 0 ? retryDelayInMs : 1000; }, shouldResetTimeout: true, retryCondition: retryCondition }); } _createClass(FulfillerIdentityClient, [{ key: 'getUrl', value: function getUrl() { return this.baseUrl; } /** * Returns an array of fulfiller objects that meet the criteria expesses in options * @param options Criteria for the query * { * showArchived: boolean * fulfillerName: string * noCache: boolean * } */ }, { key: 'getFulfillers', value: function getFulfillers(options) { return this.xrayPRoxy.capturePromise('FulfillerIdentity.getFulfillers', this._getFulfillers.bind(this), [], options); } }, { key: '_getFulfillers', value: function _getFulfillers(authorization, subsegment, options) { var queryParameters = []; if (options && options.showArchived) queryParameters.push('showArchived=' + options.showArchived); if (options && options.fulfillerName) queryParameters.push('fulfillerName=' + options.fulfillerName); if (options && options.noCache) queryParameters.push('noCache=' + Math.random()); var url = this.baseUrl + '/v1/fulfillers' + (queryParameters.length ? "?" + queryParameters.join('&') : ""); return this.makeRequest(authorization, 'GET', url).then(function (res) { subsegment.addMetadata("response", res.data); return res.data; }).then(function (parsedBody) { return parsedBody.map(function (f) { return new Fulfiller(f.fulfillerId, f.internalFulfillerId, f.name, f.email, f.phone, f.language, f.links, f.archived); }); }).catch(function (err) { return Promise.reject(new Error("Unable to get fulfillers: " + err.message)); }); } /** * Returns an array of fulfiller objects that meet the criteria expesses in options * @param fulfillerId Id of the fulfiller to retrieve * @param options Criteria for the query * { * noCache: boolean * } */ }, { key: 'getFulfiller', value: function getFulfiller(fulfillerId, options) { return this.xrayPRoxy.capturePromise('FulfillerIdentity.getFulfillerById', this._getFulfiller.bind(this), [], fulfillerId, options); } }, { key: '_getFulfiller', value: function _getFulfiller(authorization, subsegment, fulfillerId, options) { var queryParameters = []; if (options && options.noCache) queryParameters.push('noCache=' + Math.random()); var url = this.baseUrl + '/v1/fulfillers/' + fulfillerId + (options && options.noCache ? '?noCache=' + Math.random() : ""); subsegment.addAnnotation("FulfillerId", fulfillerId); return this.makeRequest(authorization, 'GET', url).then(function (res) { subsegment.addMetadata("response", res.data); return res.data; }).then(function (f) { return new Fulfiller(f.fulfillerId, f.internalFulfillerId, f.name, f.email, f.phone, f.language, f.links, f.archived); }).catch(function (err) { if (err.response && err.response.status === 403) { return Promise.reject(new ForbiddenError('You are forbidden from reading the details of fulfiller ' + fulfillerId)); } else if (err.response && err.response.status === 404) { return Promise.reject(new FulfillerNotFoundError('Fulfiller ' + fulfillerId + ' does not exist')); } return Promise.reject(new Error("Unable to get fulfiller: " + err.message)); }); } /** * Returns an array of fulfiller objects that meet the criteria expesses in options * @param fulfillerId Id of the fulfiller to retrieve * @param options Criteria for the query * { * noCache: boolean * } */ }, { key: 'getFulfillerContacts', value: function getFulfillerContacts(fulfillerId, options) { return this.xrayPRoxy.capturePromise('FulfillerIdentity.getFulfillerContacts', this._getFulfillerContacts.bind(this), [], fulfillerId, options); } }, { key: '_getFulfillerContacts', value: function _getFulfillerContacts(authorization, subsegment, fulfillerId, options) { var url = this.baseUrl + '/v1/fulfillers/' + fulfillerId + '/contacts' + (options && options.noCache ? '?noCache=' + Math.random() : ""); subsegment.addAnnotation("FulfillerId", fulfillerId); return this.makeRequest(authorization, 'GET', url).then(function (res) { subsegment.addMetadata("response", res.data); return res.data; }).then(function (parsedBody) { return parsedBody.map(function (f) { return new FulfillerContact(f.id, f.createdAt, f.createdBy, f.defaultContact, f.email, f.language, f.name, f.phone, f.technicalContact, f.businessContact, f.operationalSupportContact, f.links); }); }).catch(function (err) { if (err.response && err.response.status === 403) { return Promise.reject(new ForbiddenError('You are forbidden from reading the details of fulfiller ' + fulfillerId)); } else if (err.response && err.response.status === 404) { return Promise.reject(new FulfillerNotFoundError('Fulfiller ' + fulfillerId + ' does not exist')); } return Promise.reject(new Error("Unable to get fulfiller contacts: " + err.message)); }); } /** * Saves changes made to a fulfiller object. * @param fulfiller Fufiller object, either retrieved via getFulfiller or getFulfillers or using new Fulfiller statement */ }, { key: 'saveFulfiller', value: function saveFulfiller(fulfiller) { return this.xrayPRoxy.capturePromise('FulfillerIdentity.saveFulfiller', this._saveFulfiller.bind(this), [], fulfiller); } }, { key: '_saveFulfiller', value: function _saveFulfiller(authorization, subsegment, fulfiller) { var fulfillerId = fulfiller.fulfillerId || fulfiller.internalFulfillerId; if (fulfillerId) { subsegment.addAnnotation("FulfillerId", fulfillerId); return this.makeRequest(authorization, 'PUT', this.baseUrl + '/v1/fulfillers/' + fulfillerId, fulfiller).then(function (f) { return Promise.resolve(); }).catch(function (err) { return Promise.reject(new Error("Unable to update fulfiller: " + err.message)); }); } else { return this.makeRequest(authorization, 'POST', this.baseUrl + '/v1/fulfillers', fulfiller).then(function (f) { return Promise.resolve(); }).catch(function (err) { return Promise.reject(new Error("Unable to create fulfiller: " + err.message)); }); } } }, { key: 'makeRequest', value: function makeRequest(authorization, method, url, body) { var params = { timeout: this.timeout, method: method, url: url, headers: { 'Content-Type': 'application/json' } }; if (authorization) { params.headers.Authorization = authorization; } if (body) { params.data = body; } return axios(params); } }]); return FulfillerIdentityClient; }(); module.exports = FulfillerIdentityClient;