UNPKG

seniorvu-sdk

Version:

JS wrapper SDK for the SeniorVu web API

324 lines (260 loc) 8.5 kB
'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var axios = _interopDefault(require('axios')); // Check if the expiration time is within a day function expiresSoon(expireAt) { if (typeof expireAt === 'undefined') { return true; } return (new Date(expireAt) - new Date()) < 1000 * 60 * 60 * 24; } var ENVIRONMENTS = { staging: 'https://api.staging.seniorvu.com', prod: 'https://api.seniorvu.com', }; var DEFAULT_OPTS = {}; var PATHS = [ 'address', 'amenities', 'analyticsUrl', 'appointments', 'archivedLeads', 'assets', 'available', 'awsSettings', 'batchCreate', 'calls', 'carers', 'cartItems', 'claimRequests', 'communities', 'deleteCreated', 'deviceTokens', 'events', 'forgotPassword', 'hours', 'image', 'leads', 'me', 'neighborhoods', 'password', 'payment', 'predict', 'priorities', 'proximity', 'purchasedLeads', 'reset', 'reviews', 'rooms', 'statuses', 'tasks', 'tours', 'upload', 'users', 'video', 'webhook' ]; var SeniorVu = function SeniorVu(opts, ax) { var this$1 = this; if ( opts === void 0 ) opts = {}; if (ax) { this.ax = ax; } else { this.ax = axios.create(); } this.config(opts); // Create functions for each XHR verb ['get', 'post', 'put', 'delete'].forEach(function (verb) { this$1[verb] = function (body) { opts = {}; opts.method = verb; var segments = this$1.chain && this$1.chain.segments ? this$1.chain.segments : []; opts.url = [this$1.opts.baseUrl].concat('api', segments).join('/'); opts.params = this$1.chain.params; opts.data = body; if (verb === 'get') { opts.params = Object.assign({}, opts.params, body || {}); } // Clear chain for reuse this$1.chain = null; // Should we catch a possible expired token here or let consumer handle it?? var refresh = expiresSoon(this$1.expireAt) ? this$1.refreshToken() : Promise.resolve(); return refresh .then(function () { return this$1.ax(opts); }) .then(function (res) { return ((res && res.data) ? res.data : res); }); }; }); this._buildMethods(); }; // NOTE: expose for tests. Should be a better way but mixing default/named exports is a no-no SeniorVu.prototype.expiresSoon = function expiresSoon$1 () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return expiresSoon.apply(void 0, args); }; SeniorVu.prototype.config = function config (opts) { if ( opts === void 0 ) opts = {}; this.opts = this.opts || {}; if (!opts.baseUrl && opts.env && opts.env.indexOf('staging') === 0) { this.opts.baseUrl = ENVIRONMENTS.staging; } else if (!opts.baseUrl && opts.env && opts.env.indexOf('prod') === 0) { this.opts.baseUrl = ENVIRONMENTS.prod; } // Delete any null props from the passed-in options for (var i = 0, list = Object.keys(opts); i < list.length; i += 1) { var prop = list[i]; if (opts[prop] === null) { delete opts[prop]; } } Object.assign(this.opts, DEFAULT_OPTS, opts); if (!this.opts.baseUrl) { this.opts.baseUrl = ENVIRONMENTS.prod; } // Handle incoming token if (this.opts.token) { this._updateToken(this.opts.token); } if (this.opts.expireAt) { this.expireAt = this.opts.expireAt; } return this; }; SeniorVu.prototype.authenticate = function authenticate (opts) { var this$1 = this; if ( opts === void 0 ) opts = {}; opts = Object.assign({}, this.opts, opts); // Authenticate via one-time if we have one if (opts.oneTimeToken && this._isOneTimeToken(opts.oneTimeToken)) { return this.oneTimeTokenAuth(opts.oneTimeToken); } // Auth via username and password or apiKey if ((opts.email && opts.password) || opts.apiKey) { return axios.post(opts.baseUrl + '/auth/login', { email: opts.email, password: opts.password, apiKey: opts.apiKey, }) .then(function (res) { if (res && res.data && res.data.token) { this$1.userId = res.data.userId; this$1._updateToken(res.data.token); return { token: this$1.token, userId: this$1.userId }; } throw new Error('No token received from SeniorVu API'); }) .catch(function (error) { return this$1._handleError(error); }); } throw new Error('No authentication options provided'); }; SeniorVu.prototype.register = function register (opts) { var this$1 = this; return axios.post(this.opts.baseUrl + '/auth/registration', opts) .then(function (res) { return res.data; }) .catch(function (error) { return this$1._handleError(error); }); }; SeniorVu.prototype.oneTimeTokenAuth = function oneTimeTokenAuth (token) { var this$1 = this; return this.ax(this.opts.baseUrl + '/auth/login', { token: token, }) .then(function (res) { if (res && res.data.token) { this$1._updateToken(res.data.token); } if (res && res.data.userToken) { return { token: this$1.token, userToken: res.data.userToken, }; } }); }; SeniorVu.prototype.refreshToken = function refreshToken () { var this$1 = this; // If a token is needed then the following request will receive a 401 if (!this.token) { return Promise.resolve(); } return this.ax({ url: ((this.opts.baseUrl) + "/auth/refresh"), method: 'post', headers: { Authorization: ("Bearer " + (this.token)) }, }) .then(function (res) { if (res && res.data && res.data.token) { this$1._updateToken(res.data.token); this$1.expireAt = res.data.expireAt; } else { var e = new Error('Problem refreshing jwt'); e.response = res; throw e; } }) .catch(function (error) { return this$1._handleError(error); }); }; SeniorVu.prototype._updateToken = function _updateToken (token) { this.token = token; this.ax.defaults.headers.Authorization = "Bearer " + token; }; SeniorVu.prototype._buildMethods = function _buildMethods () { var this$1 = this; var loop = function () { var path = list[i]; this$1[path] = function (arg) { return this$1._chain(path, arg); }; }; for (var i = 0, list = PATHS; i < list.length; i += 1) loop(); }; // TODO: fix when API method exists SeniorVu.prototype._isOneTimeToken = function _isOneTimeToken (token) { return /srvu-.{12,}/.test(token); }; SeniorVu.prototype._startChain = function _startChain () { return new SeniorVuChain(this.opts, this.ax); /* eslint no-use-before-define: "off" */ }; SeniorVu.prototype._chain = function _chain () { var segments = [], len = arguments.length; while ( len-- ) segments[ len ] = arguments[ len ]; var instance = this; if (!(instance instanceof SeniorVuChain)) { instance = this._startChain(); } instance.chain = instance.chain || { segments: [] }; for (var i = 0, list = segments; i < list.length; i += 1) { var s = list[i]; if (s === null || s === undefined) { continue; } if (typeof s === 'object') { instance.chain.params = s; } else { instance.chain.segments.push(s); } } return instance; }; SeniorVu.prototype._handleError = function _handleError (err) { var ex = null; if (err.response) { if (err.response.data && err.response.data.errors && err.response.data.errors.length > 0) { var msg = err.response.data.errors[0].message || err.response.data.errors[0]; ex = new Error(msg); } else if (err.response.data) { ex = new Error(err.response.data); } else { ex = new Error('Unknown issue'); ex.err = err; } } else if (err.request) { ex = new Error('No response from SeniorVu API'); } else { ex = err; // ex = new Error('Error setting up request'); } ex.axios = err; throw ex; }; var SeniorVuChain = /*@__PURE__*/(function (SeniorVu) { function SeniorVuChain () { SeniorVu.apply(this, arguments); } if ( SeniorVu ) SeniorVuChain.__proto__ = SeniorVu; SeniorVuChain.prototype = Object.create( SeniorVu && SeniorVu.prototype ); SeniorVuChain.prototype.constructor = SeniorVuChain; SeniorVuChain.prototype.authenticate = function authenticate () { throw new Error('Cannot re-authenticate while chaining a request'); }; return SeniorVuChain; }(SeniorVu)); module.exports = SeniorVu; //# sourceMappingURL=seniorvu.cjs.js.map