import axios, { AxiosInstance } from 'axios' import { UnauthorizedError } from '@wirewheel/cmp/src/errors/UnauthorizedError' import { BadRequestError } from '@wirewheel/cmp/src/errors/BadRequestError' import { NotFoundError } from '@wirewheel/cmp/src/errors/NotFoundError' import { UnexpectedError } from '@wirewheel/cmp/src/errors/UnexpectedError' const errorMap = new Map([ [401, UnauthorizedError], [400, BadRequestError], [404, NotFoundError], [500, UnexpectedError], ]) type HttpClientConfig = { apiUrl: string token?: string apiKey?: string } export class HttpClient { private _client: AxiosInstance static create({ apiUrl, token, apiKey }: HttpClientConfig): HttpClient { return new HttpClient(apiUrl, token, apiKey) } private constructor( private readonly apiUrl: string, private readonly token?: string, private readonly apiKey?: string ) { const baseURL = new URL(this.apiUrl).href.replace(/\/$/, '') this._client = axios.create({ baseURL, headers: { ...(token && { authorization: `Bearer ${this.token}` }), ...(apiKey && { 'x-api-key': apiKey }), }, }) // FIXME(pablo): support for interceptors in mocked axios needs to be fixed this._client?.interceptors?.response?.use(undefined, this.errorHandler) } async get(resource: string, config?: any): Promise { const response = await this._client.get(resource, config) return response?.data } async post(resource: string, data: any, config?: any): Promise { const response = await this._client.post(resource, data, config) return response?.data } private errorHandler(error: any) { const status = error.response?.status const message = error.response?.data?.message const httpErrorClass = errorMap.has(status) ? errorMap.get(status) : undefined if (httpErrorClass) { throw new httpErrorClass(message) } throw error } }