-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.ts
104 lines (93 loc) · 2.29 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
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
import {
body,
createBuildEndpointFn,
method,
type TFetchFn,
type TFetchFnParams,
type TFetchTransformer,
} from "./index.js";
type Token = {
access_token: string;
scope: string;
expires_at: number;
};
const isExpired = (token: Token): boolean => {
return token.expires_at - Date.now() < 0;
};
const tokenEndpoint = (payload: {
client_id: string;
client_secret: string;
audience: string;
//...
}) => {
return {
url: "/token",
transformers: [method("POST"), body(JSON.stringify(payload))],
responseParser: (json: any): Token => json,
};
};
const createOAuth2Client = (opts: {
debug?: boolean;
credentials: { client_id: string; client_secret: string; audience: string };
}) => {
const build = createBuildEndpointFn({
baseUrl: "https://auth.example.com/oauth",
debug: !!opts.debug,
});
let cachedToken: Token | null = null;
const fetchToken = build(tokenEndpoint);
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();
return fetchFn(input, {
...init,
headers: {
...init?.headers,
Authorization: `Bearer ${token.access_token}`,
},
});
};
};
function apiAction(param: number) {
return {
url: `/some/path/${param}`,
transformers: [method("GET")],
};
}
const createApiSdk = (
oauthClient: ReturnType<typeof createOAuth2Client>,
opts: { debug?: boolean } = {},
) => {
const build = createBuildEndpointFn({
baseUrl: "https://api.example.com",
transformers: [bearerToken(oauthClient)],
debug: !!opts.debug,
});
return {
someAction: build(apiAction),
};
};
const oauth = createOAuth2Client({
credentials: {
audience: "test",
client_id: "asdasd",
client_secret: "asdasdasd",
},
});
const sdk = createApiSdk(oauth, {});
const result = await sdk.someAction(123);
const json = await result.json();
console.log(json);