-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathurl-formatter.ts
48 lines (47 loc) · 1.38 KB
/
url-formatter.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
import { InternalAxiosRequestConfig } from 'axios'
/**
* @description
* Axios interceptor. Finds tokens inside of {} in config.url, matches them by keys of config.params,
* replaces them with matched values, removes matched keys from config.params.
* Applied by default to an axios instance created by createAxiosResourceFactory
*
* @example
* ```js
* const axiosInstance = axios.create()
* axiosInstance.interceptors.request.use(interceptorUrlFormatter)
* axiosInstance.request({
* url: '/{id}',
* baseURL: 'http://localhost:3000/resource',
* method: 'POST',
* data: {
* field: 'value'
* },
* params: {
* id: '123'
* }
* })
* // interceptorUrlFormatter processes config before making an ajax request. Processed config:
* // {
* // url: '/123',
* // baseURL: 'http://localhost:3000/resource',
* // method: 'POST',
* // data: {
* // field: 'value'
* // },
* // params: {}
* // }
* ```
*/
export const interceptorUrlFormatter = (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
if (!config.params) {
return config
}
for (const paramName of Object.keys(config.params)) {
const param = config.params[paramName]
if (config.url && config.url.indexOf(`{${paramName}}`) > -1) {
config.url = config.url.replace(`{${paramName}}`, () => param)
delete config.params[paramName]
}
}
return config
}