UNPKG

@c8y/client

Version:

Client application programming interface to access the Cumulocity IoT-Platform REST services.

89 lines 3.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FetchClient = void 0; const tslib_1 = require("tslib"); const cross_fetch_1 = tslib_1.__importDefault(require("cross-fetch")); // eslint-disable-next-line prefer-const let auths = new WeakMap(); class FetchClient { constructor(authOrBaseUrl, baseUrl) { this.baseUrl = baseUrl; this.tenant = ''; this.defaultHeaders = {}; if (typeof authOrBaseUrl === 'string') { baseUrl = authOrBaseUrl; } else { this.setAuth(authOrBaseUrl); } this.baseUrl = this.resolveServerUrl(baseUrl); } setAuth(auth) { auths.set(this, auth); } async fetch(url, init) { let fetchFn = cross_fetch_1.default; try { fetchFn = window.fetch || fetchFn; } catch (e) { /* do nothing */ } const fullUrl = this.getUrl(url, init); const options = this.getFetchOptions(init); const optionsWithAdjustedBody = this.adjustOptionsForFormData(options); return fetchFn(fullUrl, optionsWithAdjustedBody); } getUrl(url = '', options) { const params = options && options.params; let paramPart = ''; if (params && Object.keys(params).length) { paramPart = Object.keys(params) .map(k => { let vals = params[k]; const encodedKey = encodeURIComponent(k); if (!Array.isArray(vals)) { vals = [vals]; } return vals.map(v => `${encodedKey}=${encodeURIComponent(v)}`).join('&'); }) .join('&'); paramPart = `?${paramPart}`; } const baseUrl = this.baseUrl.replace(/\/+$/, '').replace(/^\/+/, ''); const partialUrl = url.replace(/\/+$/, '').replace(/^\/+/, ''); return `${baseUrl}/${partialUrl}${paramPart}`; } getFetchOptions(options = {}) { let clonedOptions = { ...options }; const auth = auths.get(this); clonedOptions.headers = Object.assign({}, this.defaultHeaders, clonedOptions.headers, { UseXBasic: true }); delete clonedOptions.params; clonedOptions = auth ? auth.getFetchOptions(clonedOptions) : clonedOptions; return clonedOptions; } getCometdHandshake(config = {}) { const auth = auths.get(this); return auth ? auth.getCometdHandshake(config) : config; } resolveServerUrl(baseUrl = '') { if (baseUrl && baseUrl.startsWith('http')) { return baseUrl.replace(/\/+$/, ''); } try { const location = window.location; return `${location.protocol}//${location.host}/${baseUrl.replace(/\/+$/, '')}`; } catch (ex) { throw Error('Your environment does not support relative URLs. Please provide a base URL.'); } } adjustOptionsForFormData(options) { const newOptions = Object.assign(options, { body: options.body }); return newOptions; } } exports.FetchClient = FetchClient; //# sourceMappingURL=FetchClient.js.map