UNPKG

kalibri

Version:
83 lines (82 loc) 3.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const _types_1 = require("../_types"); const _base_adapter_1 = require("./_base.adapter"); class ClientAdapter extends _base_adapter_1.AAdapter { parseResponseText(xhr) { const headers = xhr.getAllResponseHeaders(); if (xhr.responseType === '' || xhr.responseType === 'text') { try { return headers.includes('json') ? JSON.parse(xhr.responseText) : xhr.responseText; } catch (err) { return xhr.responseText; } } return xhr.response; } successResponse(xhr) { return { ok: xhr.status >= 200 && xhr.status < 300, status: xhr.status, statusText: xhr.statusText, headers: xhr.getAllResponseHeaders(), data: this.parseResponseText(xhr), }; } errorResponse(xhr, message = '') { return { ok: false, status: xhr.status, statusText: xhr.statusText, headers: xhr.getAllResponseHeaders(), message, data: this.parseResponseText(xhr), }; } request({ requestConfig, interceptors: { beforeRequestInterceptor, afterRequestInterceptor }, }) { const { method, url, headers, timeout, body, responseType } = requestConfig; beforeRequestInterceptor(requestConfig); return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.responseType = responseType; xhr.open(method, url); if (headers) { Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key])); } xhr.timeout = timeout; xhr.onload = (evt) => { if (xhr.readyState === xhr.DONE) { if (xhr.status >= 100 && xhr.status < 400) { const result = this.successResponse(xhr); afterRequestInterceptor(result); return resolve(result); } afterRequestInterceptor(this.errorResponse(xhr)); reject(this.errorResponse(xhr)); } }; xhr.onerror = () => { reject(this.errorResponse(xhr, 'Failed to make request.')); }; xhr.ontimeout = () => { reject(this.errorResponse(xhr, 'Request took longer than expected.')); }; const needsToStringify = body instanceof Object && body !== null && !(body instanceof FormData); if ([_types_1.REQUEST_METHODS.POST, _types_1.REQUEST_METHODS.PATCH].includes(method) && needsToStringify) { xhr.setRequestHeader('Content-Type', 'application/json'); } if (needsToStringify) { return xhr.send(JSON.stringify(body)); } else if (!!body) { return xhr.send(body); } xhr.send(); }); } } exports.default = ClientAdapter;