Modelo de activacion de sim con token automatico
This commit is contained in:
@@ -1,7 +1,62 @@
|
||||
export class HTTPClient {
|
||||
import { AxiosInstance, create as axiosCreate } from "axios"
|
||||
import { JWTToken } from "../domain/JWT"
|
||||
|
||||
export type JWTProvider<T> = {
|
||||
/** El servidor está solicitando un token nuevo o refrescando el actual*/
|
||||
isRefreshing: boolean
|
||||
authToken: JWTToken<T> | undefined
|
||||
tryRefreshToken: () => Promise<JWTToken<T>>
|
||||
getAccessToken: () => Promise<JWTToken<T>>
|
||||
}
|
||||
|
||||
export class HttpClient {
|
||||
|
||||
public client: AxiosInstance
|
||||
private jwtManager: JWTProvider<{}>
|
||||
|
||||
constructor(args: {
|
||||
baseURL: string,
|
||||
headers: Object,
|
||||
jwtManager: JWTProvider<{}> // todo: asociar el tipo de token
|
||||
}) {
|
||||
this.client = axiosCreate({
|
||||
...args
|
||||
})
|
||||
|
||||
this.jwtManager = args.jwtManager
|
||||
|
||||
|
||||
this.client.interceptors.request.use(
|
||||
async (config) => {
|
||||
// Idealmente estas condiciones no deberian de darse si mantenemos el
|
||||
// token valido de forma preventiva
|
||||
const token = this.jwtManager.authToken?.rawToken
|
||||
|
||||
if (token == undefined) throw new Error("No se ha obtenido el token para la peticion")
|
||||
|
||||
config.headers.Authorization = `Bearer ${this.jwtManager.authToken!.rawToken}`
|
||||
console.log("request completa", config.headers, config.data)
|
||||
return config;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
|
||||
// No deberia usarlos de momento
|
||||
this.client.interceptors.response.use(
|
||||
(response) => {
|
||||
return response;
|
||||
},
|
||||
async (error) => {
|
||||
// TODO: Esta parte no tiene tipos, hay que asegurar el error
|
||||
const req = error.config
|
||||
console.error("[http] Error en la respuesta ", error)
|
||||
if (error.response?.status == 401) {
|
||||
this.jwtManager.getAccessToken()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
constructor() {
|
||||
// JWT?
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user