-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-http.ts
More file actions
40 lines (35 loc) · 1.02 KB
/
auth-http.ts
File metadata and controls
40 lines (35 loc) · 1.02 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
import { http } from './http';
import { httpRaw } from './http-raw';
import { unwrap } from '../unwrap';
import { AuthError } from '../errors/auth';
import { tokenStore } from '@blog/token-store';
let refreshPromise: Promise<void> | null = null;
async function refreshSession() {
const { status, body } = await httpRaw('/api/auth/refresh', {
method: 'POST',
});
if (status === 401) {
tokenStore.clear();
throw new AuthError();
}
const data = unwrap<{ accessToken: string }>(status, body);
tokenStore.set(data.accessToken);
}
export async function authHttp(
input: RequestInfo,
init: RequestInit = {},
retry = true,
): Promise<{ status: number; body: any }> {
const { status, body } = await http(input, init);
if (status === 401) {
if (!retry) return { status, body };
if (!refreshPromise) {
refreshPromise = refreshSession().finally(() => {
refreshPromise = null;
});
}
await refreshPromise;
return authHttp(input, init, false);
}
return { status, body };
}