UNPKG

simpa

Version:

Lightweight library for prototyping Single Page Applications.

93 lines 3.02 kB
"use strict"; /* MIT License * * Copyright (c) 2016-2023 Dariusz Depta * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.JsonApiService = exports.JsonApiError = void 0; class JsonApiError { code; detail; constructor() { this.code = null; this.detail = null; } } exports.JsonApiError = JsonApiError; class JsonApiService { GET(body) { return JsonApiService.prepare('GET', body, this.getAuthHeader()); } POST(body) { return JsonApiService.prepare('POST', body, this.getAuthHeader()); } PUT(body) { return JsonApiService.prepare('PUT', body, this.getAuthHeader()); } DELETE(body) { return JsonApiService.prepare('DELETE', body, this.getAuthHeader()); } call(uri, init, initCallback, dataCallback, errorCallback, errorsCallback, failureCallback, finalCallback) { initCallback(); fetch(encodeURI(uri), init) .then(response => { if (response.ok) { return response.json(); } else { return Promise.reject(response); } }) .then(response => { if (response.data) { dataCallback(response.data); } if (response.errors) { errorsCallback(response.errors); } }) .catch(reason => { if (reason instanceof Response) { errorCallback(reason); } else { failureCallback(reason); } }) .finally(() => { finalCallback(); }); } static prepare(method, body, authHeader) { let requestInit = {}; let headers = []; requestInit.method = method; requestInit.cache = 'no-cache'; requestInit.credentials = 'omit'; requestInit.redirect = 'follow'; requestInit.referrer = 'no-referrer'; if (authHeader) { headers.push(['Authorization', authHeader]); } if (body) { let payload = JSON.stringify(body); requestInit.body = payload; headers.push(['Content-Type', 'application/json']); headers.push(['Content-Length', payload.length.toString()]); } if (headers.length > 0) { requestInit.headers = headers; } return requestInit; } } exports.JsonApiService = JsonApiService; //# sourceMappingURL=services.js.map