Files
sf-sim/packages/sim-shared/infrastructure/HTTPClient.ts

77 lines
2.1 KiB
TypeScript
Raw Normal View History

import axios, { AxiosInstance } from "axios"
import { IJWTService, JWTToken } from "../domain/JWT.js"
// Cambiar por IJWRGeneralService
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<{}>
private jwtService: IJWTService<any> | undefined;
constructor(args: {
baseURL: string,
headers: Record<string, string>,
jwtManager: JWTProvider<{}> // todo: asociar el tipo de token,
jwtService?: IJWTService<any>
}) {
this.client = axios.create({
...args
})
this.jwtManager = args.jwtManager
if (args.jwtService != undefined) this.jwtService = args.jwtService
this.client.interceptors.request.use(
async (config) => {
// Idealmente estas condiciones no deberian de darse si mantenemos el
// token valido de forma preventiva
const token = await this.jwtManager.getAccessToken()
if (token == undefined) throw new Error("No se ha obtenido el token para la petición")
config.headers.Authorization = `Bearer ${this.jwtManager.authToken!.rawToken}`
console.log("request completa", 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, error.response)
if (error.response?.status == 401) {
this.jwtManager.getAccessToken()
}
2026-01-30 10:42:48 +01:00
return Promise.reject(error)
}
)
}
2026-01-26 15:04:17 +01:00
get get() {
return this.client.get
2026-01-26 15:04:17 +01:00
}
get post() {
return this.client.post
}
get patch() {
return this.client.patch
}
2026-01-26 15:04:17 +01:00
}