-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAxios.ts
49 lines (41 loc) · 1.61 KB
/
Axios.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
import axios, { AxiosInstance } from 'axios';
import HttpClient, { IRequestOption } from './IHttpClient';
import { responseTransformer, errorHandler } from './HttpTransformers.ts';
/**
* Axios API client
* @implements HttpClient
* @see HttpClient
* @summary It is used to make HTTP requests, it is asynchronous and uses promises.
* @supported Supported browsers for Axios: https://github.com/axios/axios#browser-support
*/
class Axios implements HttpClient {
axiosApi: AxiosInstance = axios.create();
domain = new URL(location.href);
defaultUrl = `${this.domain.origin}/api/v1/`;
constructor(private cache: ICache<any>) {}
public async request<Response>(option: IRequestOption): Promise<Response> {
const crfToken = document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement;
const headers = {
token: crfToken?.content || '',
...option.headers
};
const cacheKey = JSON.stringify({ url: this.defaultUrl + option.url, method: option.method, headers, data: option.body });
const cachedResponse = await this.cache.get(cacheKey);
if (cachedResponse !== null) {
return cachedResponse;
}
return this.axiosApi({
method: option.method,
url: this.defaultUrl + option.url,
data: option.body,
headers
})
.then((response) => <Response>response)
.then(async response => {
await this.cache.set(cacheKey, response);
return response;
})
.catch(errorHandler);
}
}
export default Axios;