From acc4ae52da21b5e86a45a7bfa4c8127cc5031fcf Mon Sep 17 00:00:00 2001 From: jdude700 Date: Tue, 4 Jul 2023 16:06:57 +1000 Subject: [PATCH] Moved expiry check into refresh token function in auth. --- packages/src/twitch/auth.ts | 12 ++++++++---- packages/src/twitch/helix.ts | 5 +---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/packages/src/twitch/auth.ts b/packages/src/twitch/auth.ts index f9755950..58588c64 100644 --- a/packages/src/twitch/auth.ts +++ b/packages/src/twitch/auth.ts @@ -93,17 +93,21 @@ class MacroGraphAuthProvider { async refreshAccessTokenForUser(user: string): Promise { const userId = user; - const { userName, refreshToken } = Maybe(this.tokens.get(userId)).expect( + const token = Maybe(this.tokens.get(userId)).expect( "refreshAccessTokenForUser missing token" ); - Maybe(refreshToken).expect("Refresh token is null!"); + if (Date.now() < token.obtainmentTimestamp + token.expiresIn * 1000) { + return token; + } + + Maybe(token.refreshToken).expect("Refresh token is null!"); const res = await fetch("https://macrograph.brendonovich.dev/auth/twitch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ - refreshToken, + refreshToken: token.refreshToken, }), }); @@ -115,7 +119,7 @@ class MacroGraphAuthProvider { expiresIn: data.expires_in ?? null, obtainmentTimestamp: Date.now(), userId, - userName, + userName: token.userName, }; this.tokens.set(userId, returnData); diff --git a/packages/src/twitch/helix.ts b/packages/src/twitch/helix.ts index 4d6ac2d2..0ad034a0 100644 --- a/packages/src/twitch/helix.ts +++ b/packages/src/twitch/helix.ts @@ -23,10 +23,7 @@ export const { client, userId, setUserId } = createRoot(() => { fetchFn: async (url, args) => { const user = await auth.getAccessTokenForUser(userId().unwrap()); const token = auth.tokens.get(userId().unwrap()); - if (Date.now() > token?.obtainmentTimestamp + token?.expiresIn * 1000) { - await auth.refreshAccessTokenForUser(token?.userId); - console.log("refreshing"); - } + await auth.refreshAccessTokenForUser(token?.userId); if (args.body instanceof URLSearchParams) { url = `${url}?${args.body.toString()}`; }