Created
December 9, 2018 11:02
-
-
Save dengue8830/4bcfe9cfef257753ec5afe03bbdda83b to your computer and use it in GitHub Desktop.
Http wrapper allow us changing the implementation and defining our custom http response/request interfaces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios, { AxiosInstance, AxiosPromise, AxiosRequestConfig } from 'axios'; | |
import { ErrorExtra } from '../models/errores'; | |
export class HttpError extends ErrorExtra { | |
status: HttpErrorCode; | |
constructor(status: HttpErrorCode, mensaje: string = '', extra?: any) { | |
super(mensaje, extra); | |
this.status = status; | |
// Esto quita este constructor del stacktrace pero solo esta disponible en node, no browsers | |
Error.captureStackTrace(this, ErrorExtra); | |
} | |
} | |
export enum HttpErrorCode { | |
NoAutorizado = 401 | |
} | |
export interface IHttpResponse<T> { | |
data: T; | |
} | |
class Http { | |
instance: AxiosInstance; | |
constructor() { | |
this.instance = axios.create(); | |
} | |
setCredenciales(token: string) { | |
this.instance.defaults.headers.common.Authorization = 'bearer ' + token; | |
// JWTUtils.parseJwt(resLogin.data.token).usuario.id | |
} | |
prepararError(error: any) { | |
error.extra = JSON.stringify({ | |
url: error.request.responseURL, | |
status: error.request.status, | |
method: error.config.method, | |
response: error.request.responseText, | |
}); | |
} | |
private tratarRequest<T>(axiosPromise: AxiosPromise): Promise<IHttpResponse<T>> { | |
return new Promise((resolve, reject) => { | |
axiosPromise.then(res => { | |
resolve({ data: res.data }); | |
}).catch(error => { | |
this.prepararError(error); | |
reject(new HttpError(error.request.status)); | |
}); | |
}); | |
} | |
get<T = any>(url: string, config?: AxiosRequestConfig): Promise<IHttpResponse<T>> { | |
return this.tratarRequest<T>(this.instance.get(url, config)); | |
} | |
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<IHttpResponse<T>> { | |
return this.tratarRequest<T>(this.instance.post(url, data, config)); | |
} | |
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<IHttpResponse<T>> { | |
return this.tratarRequest<T>(this.instance.put(url, data, config)); | |
} | |
delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<IHttpResponse<T>> { | |
return this.tratarRequest<T>(this.instance.delete(url, config)); | |
} | |
} | |
export const http = new Http(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment