-
Notifications
You must be signed in to change notification settings - Fork 0
/
axios-client.ts
99 lines (83 loc) · 2.35 KB
/
axios-client.ts
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import axios, { AxiosError, AxiosInstance } from "axios";
import { Logger } from "../logger/logger";
import { HttpClient } from "./http-client";
import { ApiUnkownError } from "../../errors/api-unkown-error";
import { ApiServerError } from "../../errors/api-server-error";
import { ApiBadRequestError } from "../../errors/api-bad-request-error";
import { InvalidArgumentError } from "../../errors/invalid-argument-error";
export class AxiosClient implements HttpClient {
private readonly client: AxiosInstance;
private readonly logger: Logger;
constructor(apiKey: string, logger: Logger) {
this.validateApiKey(apiKey);
this.logger = logger;
this.client = axios.create({
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"x-api-key": apiKey,
},
responseEncoding: "UTF-8",
responseType: "json",
validateStatus: (status: number) => status === 200,
});
}
private validateApiKey(apiKey: string) {
if (!apiKey || !apiKey.trim()) {
throw new InvalidArgumentError(`Invalid apiKey: <${apiKey}>`);
}
}
async put(
url: string,
payload: Record<string, unknown>,
queryParams?: Record<string, unknown>
): Promise<void> {
this.logger.debug("Sending put request", {
url,
payload,
params: queryParams,
});
try {
await this.client.put(url, payload, {
params: queryParams,
});
} catch (e) {
this.checkForErrors(e);
throw e;
}
}
async post(
url: string,
payload: Record<string, unknown>,
queryParams?: Record<string, unknown>
): Promise<Record<string, unknown>> {
this.logger.debug("Sending post request", {
url,
payload,
params: queryParams,
});
try {
const { data } = await this.client.post(url, payload, {
params: queryParams,
});
return data;
} catch (e) {
this.checkForErrors(e);
throw e;
}
}
private checkForErrors(e: unknown) {
if (e instanceof AxiosError && e.response?.status) {
const { status } = e.response;
if (status >= 400 && status < 500) {
throw new ApiBadRequestError(e.message);
}
if (status >= 500) {
throw new ApiServerError(e.message);
}
if (status != 200) {
throw new ApiUnkownError(e.message);
}
}
}
}