aboutsummaryrefslogtreecommitdiffstats
path: root/code
diff options
context:
space:
mode:
authorivarlovlie <git@ivarlovlie.no>2022-12-07 03:52:42 +0100
committerivarlovlie <git@ivarlovlie.no>2022-12-07 03:52:42 +0100
commitc52feb0ffd1d9e759ef37aef8548b3d8e4f776fc (patch)
tree16cd1fd8c3fa8606a2f2336bd8988d59076cb209 /code
parent58c8c501eb12b224ac821d2157391e6a897aee96 (diff)
downloadgreatoffice-c52feb0ffd1d9e759ef37aef8548b3d8e4f776fc.tar.xz
greatoffice-c52feb0ffd1d9e759ef37aef8548b3d8e4f776fc.zip
refactor: Cache valid-session result
Diffstat (limited to 'code')
-rw-r--r--code/app/src/routes/(main)/+layout.server.ts33
1 files changed, 29 insertions, 4 deletions
diff --git a/code/app/src/routes/(main)/+layout.server.ts b/code/app/src/routes/(main)/+layout.server.ts
index acb9c22..a4507e1 100644
--- a/code/app/src/routes/(main)/+layout.server.ts
+++ b/code/app/src/routes/(main)/+layout.server.ts
@@ -1,21 +1,22 @@
import { api_base, CookieNames } from "$lib/configuration";
import { log_debug, log_error } from "$lib/logger";
import { error, redirect } from "@sveltejs/kit";
+import { Temporal } from "temporal-polyfill";
import type { LayoutServerLoad } from "./$types";
export const load: LayoutServerLoad = async ({ route, cookies, locals }) => {
const isBaseRoute = route.id === "/(main)";
const isPublicRoute = (route.id?.startsWith("/(main)/(public)") || isBaseRoute) ?? true;
- const sessionIsValid = (await fetch(api_base("_/valid-session"), {
+ const sessionIsValid = (await cached_result<Response>("sessionCheck", 10, () => fetch(api_base("_/valid-session"), {
headers: {
Cookie: CookieNames.session + "=" + cookies.get(CookieNames.session)
}
}).catch((e) => {
log_error(e);
throw error(503, {
- message: "We are experiencing a service distruption! Have patience while we resolve the issue."
+ message: "We are experiencing a service disruption! Have patience while we resolve the issue."
})
- })).ok;
+ }))).ok;
log_debug("Base Layout loaded", {
sessionIsValid,
@@ -32,4 +33,28 @@ export const load: LayoutServerLoad = async ({ route, cookies, locals }) => {
return {
locale: locals.locale
}
-}; \ No newline at end of file
+}
+
+let resultCache = {};
+async function cached_result<T>(key: string, staleAfterSeconds: number, code: any) {
+ if (!resultCache[key]) {
+ resultCache[key] = {
+ l: 0,
+ c: undefined as T
+ }
+ }
+ const staleEpoch = ((resultCache[key]?.l ?? 0) + staleAfterSeconds);
+ const isStale = staleEpoch < Temporal.Now.instant().epochSeconds;
+ if (isStale || !resultCache[key]?.c) {
+ resultCache[key].c = await code();
+ resultCache[key].l = Temporal.Now.instant().epochSeconds;
+ }
+
+ console.log({
+ isStale,
+ cache: resultCache[key],
+ staleEpoch
+ });
+
+ return resultCache[key].c as T;
+} \ No newline at end of file