UNPKG

@minimaltech/ra-infra

Version:

Minimal Technology ReactJS Infrastructure

69 lines 2.55 kB
import { RequestMethods } from '../common'; import { stringify } from '../utilities'; const HTTP = 'http'; const HTTPS = 'https'; // ------------------------------------------------------------- export class NetworkHelper { name; logger; constructor(opts) { const { name, logger } = opts; this.name = name; this.logger = logger; this.logger?.info('Creating new network request worker instance! Name: %s', this.name); } getProtocol(url) { return url.startsWith('http:') ? HTTP : HTTPS; } // ------------------------------------------------------------- // SEND REQUEST // ------------------------------------------------------------- send(opts) { const t = new Date().getTime(); const { url, method, params, body, headers = {}, configs = {} } = opts; const props = { method, body: body instanceof FormData ? body : JSON.stringify(body), headers, ...configs, }; let requestUrl = url; if (params) { requestUrl = `${url}?${stringify(params)}`; } return new Promise((resolve, reject) => { this.logger?.info('[send] URL: %s | Props: %o', requestUrl, props); fetch(requestUrl, props) .then(rs => { this.logger?.info('[network]][send] Took: %s(ms)', new Date().getTime() - t); resolve(rs); }) .catch(reject); }); } // ------------------------------------------------------------- // GET REQUEST // ------------------------------------------------------------- get(opts) { return this.send({ ...opts, method: RequestMethods.GET }); } // ------------------------------------------------------------- // POST REQUEST // ------------------------------------------------------------- post(opts) { return this.send({ ...opts, method: RequestMethods.POST }); } // ------------------------------------------------------------- put(opts) { return this.send({ ...opts, method: RequestMethods.PUT }); } // ------------------------------------------------------------- patch(opts) { return this.send({ ...opts, method: RequestMethods.PATCH }); } // ------------------------------------------------------------- delete(opts) { return this.send({ ...opts, method: RequestMethods.DELETE }); } } //# sourceMappingURL=network.helper.js.map