-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.ts
77 lines (66 loc) · 2.05 KB
/
example.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
import { body, createEndpoint, method, prefix, type TFetchFn, type TFetchFnParams, type TFetchTransformer } from "./";
type Token = {
access_token: string;
scope: string;
expires_at: number;
};
const isExpired = (token: Token): boolean => {
return token.expires_at - Date.now() < 0;
};
const createOAuth2Client = (opts: {
debug?: boolean;
credentials: { client_id: string; client_secret: string; audience: string };
}) => {
const endpoint = createEndpoint([prefix("https://auth.example.com/oauth")]);
let cachedToken: Token | null = null;
const fetchToken = async (payload: {
client_id: string;
client_secret: string;
audience: string;
//...
}) => {
return endpoint<Token>("/token", [method("POST"), body(JSON.stringify(payload))]);
};
return {
token: async (skipCache: boolean = false): Promise<Token> => {
if (!cachedToken || skipCache || isExpired(cachedToken)) {
const data = await fetchToken(opts.credentials);
cachedToken = data;
}
return cachedToken;
},
};
};
const bearerToken = (oauthClient: ReturnType<typeof createOAuth2Client>): TFetchTransformer => {
return async (fetchFn: TFetchFn, ...args: TFetchFnParams) => {
const [input, init] = args;
const token = await oauthClient.token();
const headers = new Headers(init?.headers);
headers.set("Authorization", `Bearer ${token.access_token}`);
return fetchFn(input, {
...init,
headers,
});
};
};
type ActionResponse = {
hello: string;
};
const createApiSdk = (oauthClient: ReturnType<typeof createOAuth2Client>) => {
const endpoint = createEndpoint([prefix("https://api.example.com"), bearerToken(oauthClient)]);
return {
someAction: async (param: number) => {
return endpoint<ActionResponse>(`/some/path/${param}`, [method("GET")]);
},
};
};
const oauth = createOAuth2Client({
credentials: {
audience: "test",
client_id: "asdasd",
client_secret: "asdasdasd",
},
});
const sdk = createApiSdk(oauth);
const result = await sdk.someAction(123);
console.log(result);