1 import axios, { AxiosInstance, AxiosRequestConfig, Method } from "axios"
2 import axiosRetry from "axios-retry"
3
4 export type ClientArgs = {
5 accessToken: string
6 baseURL: string
7 maxRetries?: number
8 }
9
10 class Client {
11 private _axios: AxiosInstance
12
13 constructor({ accessToken, baseURL, maxRetries = 3 }: ClientArgs) {
14 const instance = axios.create({
15 baseURL,
16 headers: {
17 "X-FIGMA-TOKEN": accessToken,
18 },
19 })
20
21 // Typecast to any because our monorepo is using an older version of axios-retry and axios
22 axiosRetry(instance as any, {
23 retries: maxRetries,
24 retryDelay: axiosRetry.exponentialDelay,
25 })
26
27 this._axios = instance
28 }
29
30 async request(
31 method: Method,
32 url: string,
33 payload: Record<string, any> = {},
34 config?: AxiosRequestConfig
35 ) {
36 const requestConfig: AxiosRequestConfig = {
37 method,
38 url,
39 ...config,
40 }
41
42 if (["POST", "DELETE"].includes(method)) {
43 requestConfig.data = payload
44 }
45
46 const response = await this._axios.request(requestConfig)
47
48 if (Math.floor(response.status / 100) !== 2) {
49 throw response.statusText
50 }
51
52 return response.data
53 }
54 }
55
56 export default Client