import Axios, { AxiosInstance, AxiosPromise, AxiosResponse, AxiosBasicCredentials, AxiosRequestConfig } from "axios"; import Factory from "./factoryService"; import * as iziToast from "izitoast"; // import { localizeString } from "../filters/localizeFilter"; import { store, AppModel } from "@/store"; interface InterceptorRequestDelegate { (config: AxiosRequestConfig): AxiosRequestConfig; } interface InterceptorResponseDelegate { (config: AxiosResponse): AxiosResponse; } interface RequestInterceptorChangedDelegate { (item: InterceptorRequestDelegate): void; } interface ResponseInterceptorChangedDelegate { (item: InterceptorResponseDelegate): void; } export class interceptorsConfig { requestInterceptors: InterceptorRequestDelegate[] = []; responseInterceptors: InterceptorResponseDelegate[] = []; } export class sharedInterceptors extends interceptorsConfig { addRequestInterceptor(item: InterceptorRequestDelegate) { this.requestInterceptors.push(item); if (this.onRequestInterceptorChanged) this.onRequestInterceptorChanged(item); } addresponseInterceptor(item: InterceptorResponseDelegate) { this.responseInterceptors.push(item); if (this.onResponseInterceptorChanged) this.onResponseInterceptorChanged(item); } onRequestInterceptorChanged: RequestInterceptorChangedDelegate; onResponseInterceptorChanged: ResponseInterceptorChangedDelegate; } Factory.Register(sharedInterceptors); export function to(promise) { return promise.then(data => data) .catch(err => err.response); } export class baseRestService { public errorsToShow: number[] = [404, 500]; protected allwaysSendAuthenticationToken: boolean = false; protected saveToSessionStorage: boolean = false; private _interceptors: sharedInterceptors; set interceptors(value: interceptorsConfig) { for (let i in value.requestInterceptors) this.http.interceptors.request.use(value.requestInterceptors[i]); for (let i in value.responseInterceptors) this.http.interceptors.response.use(value.responseInterceptors[i]); } baseUrl: string = ""; OnError: OnErrorDelegate; OnHeadersPreparing: OnHeadersPreparingDelegate; protected http: AxiosInstance; constructor() { this.http = Axios.create(); this._interceptors = Factory.Get(sharedInterceptors); // Initialize preregistered interceptors for (let i in this._interceptors.requestInterceptors) this.http.interceptors.request.use(this._interceptors.requestInterceptors[i]); for (let i in this._interceptors.responseInterceptors) this.http.interceptors.response.use(this._interceptors.responseInterceptors[i]); this._interceptors.onRequestInterceptorChanged = (i) => this.http.interceptors.request.use(i); this._interceptors.onResponseInterceptorChanged = (i) => this.http.interceptors.response.use(i); // toast exception interceptors this.http.interceptors.response.use(null, r => { if (!r.status) r = r.response; var isLogged = ((store.state as AppModel).currentUser != null); if (r && (r.status >= 500 || this.errorsToShow.indexOf(r.status) >= 0 || (r.status == 401 && isLogged))) { (iziToast as any).error({ title: r.config.url, message: r.statusText, theme: "dark", timeout: 10000, class: "t-error", transitionIn: "fadeIn", transitionOut: "fadeOut", }) } else if (r && (r.status >= 400) && (r.status != 401)) { var msg = (r.data.message != null) ? (store.getters.getLabel(r.data.message) || r.data.message) : "Generic error"; (iziToast as any).error({ title: r.config.url, message: msg, theme: "dark", timeout: 10000, class: "t-error", transitionIn: "fadeIn", transitionOut: "fadeOut", }) } if (!r) { (iziToast as any).error({ title: "Comunication Error", // message: "Comunication Error", theme: "dark", class: "t-error", transitionIn: "fadeIn", transitionOut: "fadeOut", timeout: 10000 }) } return Promise.reject(r); }) } protected async upload(uri: string, filedata: Blob, filename: string, params: object = {}): Promise { let data = new FormData(); data.append('file', filedata, filename); let headers = this.prepareHeaders(true, false); headers["content-type"] = "multipart/form-data"; let response = await this.http.post(uri, data, { headers: headers, params :params } as AxiosRequestConfig); return response; } protected async get(uri: string, sendAuthenticationToken: boolean = false, params: object = {}): Promise { let response = await this.http.get(this.baseUrl + uri, { headers: this.prepareHeaders(this.allwaysSendAuthenticationToken || sendAuthenticationToken, false), params: params } as AxiosRequestConfig); return response; }; protected async Get(uri: string, sendAuthenticationToken: boolean = false, params: object = {}): Promise { let result = await this.get(uri, sendAuthenticationToken, params); if (result.status == 200) return result.data as TResult; return null; } protected async post(uri: string, data: any, sendAuthenticationToken: boolean = false): Promise { let response = await this.http.post(this.baseUrl + uri, data, { headers: this.prepareHeaders(this.allwaysSendAuthenticationToken || sendAuthenticationToken, true) }); return response; }; protected async Post(uri: string, data: any, sendAuthenticationToken: boolean = false): Promise { let result = await this.post(uri, data, sendAuthenticationToken); if (result.status == 200) return result.data as TResult; return null; } protected async put(uri: string, data: any, sendAuthenticationToken: boolean = false): Promise { let response = await this.http.put(this.baseUrl + uri, JSON.stringify(data), { headers: this.prepareHeaders(this.allwaysSendAuthenticationToken || sendAuthenticationToken, true) }); return response; } protected async Put(uri: string, data: any, sendAuthenticationToken: boolean = false): Promise { let result = await this.put(uri, data, sendAuthenticationToken); if (result.status == 200) return result.data as TResult; return null; } protected async delete(uri: string, sendAuthenticationToken: boolean = false): Promise { let response = await this.http.delete(this.baseUrl + uri, { headers: this.prepareHeaders(this.allwaysSendAuthenticationToken || sendAuthenticationToken, false) }); return response; } protected async Delete(uri: string, sendAuthenticationToken: boolean = false): Promise { let result = await this.delete(uri, sendAuthenticationToken); if (result.status == 200) return result.data as TResult; return null; } private prepareHeaders(auth: boolean = false, json: boolean = false): any { let headers = {} if (auth) { let authData = JSON.parse((this.saveToSessionStorage ? window.sessionStorage.getItem("authorizationData") : window.localStorage.getItem("authorizationData")) || null) as AuthToken; if (authData) { headers["Authorization"] = 'Bearer ' + authData.access_token; // headers.append('Authorization', 'Bearer ' + authData.access_token); } } // if (json) headers.append('Content-Type', 'application/json'); if (json) headers['Content-Type'] = 'application/json'; if (this.OnHeadersPreparing) this.OnHeadersPreparing(headers); return headers; } protected getAuthenticationToken(): AuthToken { let wstore = window.sessionStorage; let sstore = window.localStorage; return JSON.parse(wstore.getItem("authorizationData") || sstore.getItem("authorizationData") || null) as AuthToken } protected setAuthenticationToken(data: AuthToken) { let storage: any = this.saveToSessionStorage ? window.sessionStorage : window.localStorage; storage.setItem("authorizationData", JSON.stringify(data)); } protected deleteAuthenticationToken() { window.sessionStorage.setItem("authorizationData", null); window.localStorage.setItem("authorizationData", null); } } export interface OnErrorDelegate { (data: DataResponse): void; } interface OnHeadersPreparingDelegate { (headers: any): void; } export class AuthToken { access_token: string; refresh_token: string; userName: string; } export class DataResponse { status: number; statusText: string; data: any; }