UNPKG

@stylusapparel/stylusop-api-node-wrapper

Version:

This is the official NodeJs wrapper for connecting to the StylusOP API

72 lines (67 loc) 1.8 kB
const __urlConfig = require('../constants/url'); const { __defaults } = require('../constants/url'); /** * Creates an Http client object based on the auth configuration provided * @param {String} _token * @param {Object|undefined} config * For example: * { * "sandBox": false, * "username": [User's "username"], * "apiVersion": "v2", * "tokenType": "basic" * } * @returns Object */ const HttpClient = (_token, config = {}) => { const { sandBox = false, username = '', apiVersion = __defaults.LATEST_VERSION, tokenType = 'basic' } = config; const _envType = sandBox ? 'sandbox' : 'production'; const _url = __urlConfig[_envType]; // If the "STYLUSOP_API_URL" is set in the environment, use it as the base URL const _baseAPIUrl = process.env.STYLUSOP_API_URL || _url.API_URL; // Axios settings -------------- const _configuration = { baseURL: _baseAPIUrl + apiVersion, timeout: 30000, }; if (tokenType === 'jwt') { // "Bearer Token" based auth _configuration.headers = { Authorization: 'Bearer ' + _token, }; } else { // Assuming "Basic" Auth _configuration.auth = { username: username, password: _token, }; } const http = require('axios').create(_configuration); return { get: async (url) => { try { const res = await http.get(url); return res; } catch (e) { throw e; } }, post: async (url, data) => { try { const res = await http.post(url, data); return res; } catch (e) { throw e; } }, patch: async (url, data) => { try { const res = await http.patch(url, data); return res; } catch (e) { throw e; } }, }; }; module.exports = HttpClient;