-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathcustom-status-codes.ts
More file actions
74 lines (60 loc) · 2.23 KB
/
custom-status-codes.ts
File metadata and controls
74 lines (60 loc) · 2.23 KB
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
/**
* Custom Status Codes Example
*
* Demonstrates:
* (a) statusCodes: [401, 403] — refresh triggers on 403
* (b) shouldRefresh callback — inspects the error body to decide
*/
import axios, { AxiosError } from 'axios';
import { createAuthRefresh } from '../src/index';
import { createMockAdapter, MockState } from './_helpers/mock-adapter';
import { assertEqual } from './_helpers/assert';
// --- (a) statusCodes: [401, 403] ---
async function testStatusCodes() {
const state: MockState = { validToken: 'token-v2', refreshCount: 0 };
const instance = axios.create({
adapter: createMockAdapter(state, { errorStatus: 403 }),
headers: { Authorization: 'Bearer token-v1' },
});
createAuthRefresh(
instance,
async (failedRequest) => {
state.refreshCount++;
state.validToken = 'token-v2';
failedRequest.response.config.headers['Authorization'] = `Bearer ${state.validToken}`;
},
{ statusCodes: [401, 403] },
);
const response = await instance.get('/protected');
assertEqual(response.status, 200, '(a) Should refresh on 403');
assertEqual(state.refreshCount, 1, '(a) Refresh called once');
}
// --- (b) shouldRefresh callback ---
async function testShouldRefresh() {
const state: MockState = { validToken: 'token-v2', refreshCount: 0 };
const instance = axios.create({
adapter: createMockAdapter(state),
headers: { Authorization: 'Bearer token-v1' },
});
createAuthRefresh(
instance,
async (failedRequest) => {
state.refreshCount++;
state.validToken = 'token-v2';
failedRequest.response.config.headers['Authorization'] = `Bearer ${state.validToken}`;
},
{
shouldRefresh: (error: AxiosError<{ message: string }>) =>
error?.response?.data?.message === 'Invalid token',
},
);
const response = await instance.get('/protected');
assertEqual(response.status, 200, '(b) shouldRefresh matched');
assertEqual(state.refreshCount, 1, '(b) Refresh called once');
}
async function main() {
await testStatusCodes();
await testShouldRefresh();
console.log(' PASS custom-status-codes');
}
main();