UNPKG

@betha-plataforma/estrutura-componentes

Version:

Coleção de Web Components para compor a estrutura de uma aplicação front-end da Betha Sistemas.

37 lines (36 loc) 1.54 kB
import { isNill } from '../utils/functions'; const UNAUTHORIZED_STATUS_CODE = 401; export const isValidAuthorizationConfig = (authorization) => { if (isNill(authorization)) { return false; } return !isNill(authorization.getAuthorization) && !isNill(authorization.handleUnauthorizedAccess); }; export class Api { constructor(authorization, handleUnauthorizedAccess, baseUrl) { this.authorization = authorization; this.handleUnauthorizedAccess = handleUnauthorizedAccess; this.baseUrl = baseUrl; } async request(method, path, retryUnauthorizedAccess = true) { return await fetch(`${this.baseUrl}/${path}`, { method, headers: this.getHeaders() }) .then(async (response) => { if (response.status === UNAUTHORIZED_STATUS_CODE && retryUnauthorizedAccess && this.handleUnauthorizedAccess !== undefined) { await this.handleUnauthorizedAccess(); return await this.request(method, path, false); } if (response.status < 200 || response.status >= 300) { throw new Error(response.statusText); } return Promise.resolve(response); }); } getHeaders() { const headers = new Headers(); headers.append('Authorization', 'bearer ' + this.authorization.accessToken); if (this.authorization.userAccess !== undefined) { headers.append('User-Access', this.authorization.userAccess); } return headers; } }