Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 2x 2x 2x 2x 2x 2x 2x 21x 21x 21x 21x 21x 21x 21x 6x 6x 10x 10x | 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<any> {
const response = await this._client.get(resource, config)
return response?.data
}
async post(resource: string, data: any, config?: any): Promise<any> {
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
Iif (httpErrorClass) {
throw new httpErrorClass(message)
}
throw error
}
}
|