From 140f9d566b05662d4fded15f549ce3e1383e6fc7 Mon Sep 17 00:00:00 2001 From: Katalina Okano Date: Tue, 1 Feb 2022 21:05:48 -0500 Subject: [PATCH] debounce session fetch as it literally ddoses cloudflare --- .../src/contexts/session/SessionContext.tsx | 64 +++++++++++-------- 1 file changed, 38 insertions(+), 26 deletions(-) diff --git a/packages/web/src/contexts/session/SessionContext.tsx b/packages/web/src/contexts/session/SessionContext.tsx index fd75e30..376b6da 100644 --- a/packages/web/src/contexts/session/SessionContext.tsx +++ b/packages/web/src/contexts/session/SessionContext.tsx @@ -31,6 +31,16 @@ const SessionContext = React.createContext({ setupSession: () => {}, }); +const debounce = (func: Function, timeout = 300) => { + let timer: any | undefined = undefined; + return (...args: any) => { + clearTimeout(timer); + timer = setTimeout(() => { + func.apply(this, args); + }, timeout); + }; +}; + export const useSessionContext = () => React.useContext(SessionContext); export const SessionContextProvider = (props: { children: React.ReactNode }) => { @@ -108,34 +118,36 @@ export const SessionContextProvider = (props: { children: React.ReactNode }) => // If not, lets fetch it from the server setLock(true); - fetchSession(session.sessionID) - .then((sessionData) => { - if (sessionData) { - setSession({ - ...session, - isAuthenticated: true, - session: { - user: sessionData.user, - guilds: sessionData.guilds, - }, - }); - saveSessionData({ - sessionID: session.sessionID!, - session: { - user: sessionData.user, - guilds: sessionData.guilds, - }, - }); - } else { + debounce(async (sessionID: string) => { + fetchSession(sessionID) + .then((sessionData) => { + if (sessionData) { + setSession({ + ...session, + isAuthenticated: true, + session: { + user: sessionData.user, + guilds: sessionData.guilds, + }, + }); + saveSessionData({ + sessionID: session.sessionID!, + session: { + user: sessionData.user, + guilds: sessionData.guilds, + }, + }); + } else { + session.setupSession(null); + setLock(false); + } + }) + .catch((e) => { + console.error(e); session.setupSession(null); setLock(false); - } - }) - .catch((e) => { - console.error(e); - session.setupSession(null); - setLock(false); - }); + }); + }, 2000)(session.sessionID!); } }, [session, locked, setLock, fetch]);