This repository has been archived by the owner on May 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.ts
43 lines (41 loc) · 1.53 KB
/
helpers.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
const token_kv_key = "CLIENT_CRED_TOKEN";
/**
* Assuming env vars are set up correctly, returns a valid client credential.
* You would use this via `fetch` like so:
* ```js
* fetch('discord.com/api/something`, {
* headers: {'Authorization': `Bearer ${(await getClientCredentialToken())}`}
* }}
* @returns {string} - The auth token itself
* ```
*/
export async function getClientCredentialToken() {
if (typeof CONFIG_KV_NAMESPACE !== 'undefined') {
let token = await CONFIG_KV_NAMESPACE.get(token_kv_key, 'text');
if (token) {
return token;
}
}
let json = await (await fetch('https://discord.com/api/v8/oauth2/token', {
body: new URLSearchParams({
grant_type: 'client_credentials',
scope: 'applications.commands.update'
}),
method: "POST",
headers: {
'content-type': 'application/x-www-form-urlencoded',
'authorization': `Basic ${btoa(`${CLIENT_ID}:${CLIENT_SECRET}`)}`
}
})).json();
let token = json.access_token;
if (typeof CONFIG_KV_NAMESPACE !== 'undefined') {
let exp = json.expires_in
// I think Discord itself caches the token, not sure when it resets toa new one.
if (json.expires_in > 60) {
// giving the expired token 10 seconds of buffer to ensure CF clears our old token from KV before it expires
exp = json.expires_in - 10
}
await CONFIG_KV_NAMESPACE.put(token_kv_key, token, {expirationTtl: exp})
}
return token;
}