-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathfetch-wrapper.ts
117 lines (97 loc) · 2.79 KB
/
fetch-wrapper.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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import * as assert from 'node:assert';
import { OAuth2Fetch, OAuth2Client } from '../src';
import { describe, it } from 'node:test';
describe('FetchWrapper', () => {
it('should use the token from getNewToken', async () => {
const client = new OAuth2Client({
clientId: 'foo',
clientSecret: 'bar',
});
const fetchWrapper = new OAuth2Fetch({
client,
getNewToken: () => {
return {
accessToken: 'access',
refreshToken: 'refresh',
expiresAt: Date.now() + 1000_0000,
};
},
});
const mw = fetchWrapper.mw();
const response = await mw(
new Request('http://example/'),
(req): any => req
);
assert.equal(response.headers.get('Authorization'), 'Bearer access');
});
it("should use the token even if it's delayed", async () => {
const client = new OAuth2Client({
clientId: 'foo',
clientSecret: 'bar',
});
const fetchWrapper = new OAuth2Fetch({
client,
getNewToken: async () => {
await new Promise((res) => setTimeout(res, 200));
return {
accessToken: 'access',
refreshToken: 'refresh',
expiresAt: Date.now() + 1000_0000,
};
},
});
const mw = fetchWrapper.mw();
const response = await mw(
new Request('http://example/'),
(req): any => req
);
assert.equal(response.headers.get('Authorization'), 'Bearer access');
});
it('should use a token from getStoredToken', async () => {
const client = new OAuth2Client({
clientId: 'foo',
clientSecret: 'bar',
});
const fetchWrapper = new OAuth2Fetch({
client,
getNewToken: () => null,
getStoredToken: () => {
return {
accessToken: 'access',
refreshToken: 'refresh',
expiresAt: Date.now() + 1000_0000,
};
},
});
const mw = fetchWrapper.mw();
const response = await mw(
new Request('http://example/'),
(req): any => req
);
assert.equal(response.headers.get('Authorization'), 'Bearer access');
});
it("should still work with getStoredToken even if it's delayed", async () => {
const client = new OAuth2Client({
clientId: 'foo',
clientSecret: 'bar',
});
const fetchWrapper = new OAuth2Fetch({
client,
getNewToken: () => null,
getStoredToken: async () => {
await new Promise((res) => setTimeout(res, 200));
return {
accessToken: 'access',
refreshToken: 'refresh',
expiresAt: Date.now() + 1000_0000,
};
},
});
const mw = fetchWrapper.mw();
const response = await mw(
new Request('http://example/'),
(req): any => req
);
assert.equal(response.headers.get('Authorization'), 'Bearer access');
});
});