diff options
| author | ivar <i@oiee.no> | 2024-04-28 22:37:30 +0200 |
|---|---|---|
| committer | ivar <i@oiee.no> | 2024-04-28 22:37:30 +0200 |
| commit | ced66c5807575cd29f6aa5632e8ad02b38c8448a (patch) | |
| tree | 01760648ee293a2aef2288328014b5747d2192b4 /code/frontend/src/hooks.server.ts | |
| parent | 691ad60d7bff5934053d87267c4e303ef3ed5f97 (diff) | |
| download | greatoffice-ced66c5807575cd29f6aa5632e8ad02b38c8448a.tar.xz greatoffice-ced66c5807575cd29f6aa5632e8ad02b38c8448a.zip | |
WIP new frontend
Diffstat (limited to 'code/frontend/src/hooks.server.ts')
| -rw-r--r-- | code/frontend/src/hooks.server.ts | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/code/frontend/src/hooks.server.ts b/code/frontend/src/hooks.server.ts new file mode 100644 index 0000000..b636e31 --- /dev/null +++ b/code/frontend/src/hooks.server.ts @@ -0,0 +1,48 @@ +import {CookieNames} from "$configuration"; +import {detectLocale, i18n, isLocale, locales} from "$i18n/i18n-util"; +import type {Handle, RequestEvent} from "@sveltejs/kit"; +import {initAcceptLanguageHeaderDetector} from "typesafe-i18n/detectors"; +import type {Locales} from "$i18n/i18n-types"; +import {loadAllLocales} from "$i18n/i18n-util.sync"; + +loadAllLocales(); +const L = i18n(); + +export const handle: Handle = async ({event, resolve}) => { + const localeCookie = event.cookies.get(CookieNames.locale); + const preferredLocale = getPreferredLocale(event); + let finalLocale = localeCookie ?? preferredLocale; + let forceCookieSet = false; + + console.debug("Handling locale", { + locales, + localeCookie, + preferredLocale, + finalLocale, + }); + + if (!isLocale(finalLocale)) { + console.debug(finalLocale + " is not a valid locale or it does not exist, switching to default: en"); + finalLocale = "en"; + forceCookieSet = true; + } + + if (!localeCookie || forceCookieSet) { + // Set a locale cookie + event.cookies.set(CookieNames.locale, finalLocale, { + sameSite: "strict", + path: "/", + httpOnly: false, + }); + } + + event.locals.locale = finalLocale as Locales; + event.locals.LL = L[finalLocale as Locales]; + + return resolve(event, {transformPageChunk: ({html}) => html.replace("%lang%", finalLocale)}); +}; + +function getPreferredLocale(event: RequestEvent) { + const acceptLanguageDetector = initAcceptLanguageHeaderDetector(event.request); + return detectLocale(acceptLanguageDetector); +} |
