|
1 | 1 | import type { AxiosError, InternalAxiosRequestConfig } from 'axios'; |
2 | 2 |
|
3 | | -import { useAuth } from '@/core'; |
| 3 | +import { signIn, useAuth } from '@/core'; |
4 | 4 |
|
5 | 5 | import { client } from './client'; |
6 | 6 | import { toCamelCase, toSnakeCase } from './utils'; |
7 | 7 |
|
| 8 | +const ACCESS_TOKEN = 'access-token'; |
| 9 | +const CLIENT_HEADER = 'client'; |
| 10 | +const UID_HEADER = 'uid'; |
| 11 | +const EXPIRY_HEADER = 'expiry'; |
| 12 | +const AUTHORIZATION_HEADER = 'Authorization'; |
| 13 | + |
| 14 | +const CONTENT_TYPE = 'Content-Type'; |
| 15 | +const MULTIPART_FORM_DATA = 'multipart/form-data'; |
| 16 | + |
8 | 17 | export default function interceptors() { |
9 | | - const token = useAuth.getState().token; |
10 | 18 | client.interceptors.request.use((config: InternalAxiosRequestConfig) => { |
11 | | - if (config.data) { |
| 19 | + const token = useAuth.getState().token; |
| 20 | + |
| 21 | + const { headers, data } = config; |
| 22 | + |
| 23 | + if (headers && headers[CONTENT_TYPE] !== MULTIPART_FORM_DATA && data) { |
12 | 24 | config.data = toSnakeCase(config.data); |
13 | 25 | } |
| 26 | + |
14 | 27 | if (token) { |
15 | | - config.headers.Authorization = `Bearer ${token}`; |
| 28 | + const { access, client: _client, uid, bearer, expiry } = token; |
| 29 | + |
| 30 | + config.headers[AUTHORIZATION_HEADER] = bearer; |
| 31 | + config.headers[ACCESS_TOKEN] = access; |
| 32 | + config.headers[CLIENT_HEADER] = _client; |
| 33 | + config.headers[UID_HEADER] = uid; |
| 34 | + config.headers[EXPIRY_HEADER] = expiry; |
16 | 35 | } |
| 36 | + |
17 | 37 | return config; |
18 | 38 | }); |
19 | 39 |
|
20 | 40 | client.interceptors.response.use( |
21 | 41 | (response) => { |
| 42 | + const { data, headers } = response; |
22 | 43 | response.data = toCamelCase(response.data); |
| 44 | + |
| 45 | + const token = headers[ACCESS_TOKEN]; |
| 46 | + const _client = headers[CLIENT_HEADER]; |
| 47 | + const uid = headers[UID_HEADER]; |
| 48 | + const expiry = headers[EXPIRY_HEADER]; |
| 49 | + const bearer = headers[AUTHORIZATION_HEADER]; |
| 50 | + |
| 51 | + if (token) { |
| 52 | + signIn({ access: token, client: _client, uid, expiry, bearer }); |
| 53 | + } |
| 54 | + |
| 55 | + response.data = toCamelCase(data); |
| 56 | + |
23 | 57 | return response; |
24 | 58 | }, |
25 | 59 | (error: AxiosError) => Promise.reject(error), |
|
0 commit comments