UNPKG

correios-webservice

Version:
55 lines 1.77 kB
import axios from "axios"; import { AuthPostcard } from "./auth"; class Http { auth; _http; apiVersion; baseUrl; constructor(auth, config) { this.auth = auth; this.apiVersion = config.apiVersion; this.baseUrl = config.baseURL; this._http = axios.create({ baseURL: `${config.baseURL}${config.prefix}`, }); this._http.interceptors.request.use((config) => { if (this.auth.getToken()) config.headers.Authorization = `Bearer ${this.auth.getToken()}`; return config; }); } async get(endpoint, params = {}, retry = true, apiVersion = this.apiVersion) { try { if (!this.auth.getToken()) await this.authenticate(); const response = await this._http.get(`/${apiVersion}${endpoint}`, { params, }); return response.data; } catch (e) { const error = e; if (error.status === 403 && retry) { await this.authenticate(); return await this.get(endpoint, params, false); } throw error; } } async authenticate() { if (this.auth instanceof AuthPostcard) { const response = await axios.post(`/token/${this.apiVersion}/autentica/cartaopostagem`, { numero: this.auth.postCardNumber, }, { baseURL: this.baseUrl, auth: { username: this.auth.userName, password: this.auth.accessToken, }, }); this.auth.setToken(response.data.token); } } } export { Http }; //# sourceMappingURL=http.js.map