aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/+layout.server.ts
blob: c1f77695daa274c5d0bec2906010dac7cf5220b4 (plain) (blame)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import {
	defaultLocale,
	loadTranslations,
	locales,
} from "$lib/translations/index";
import { auth, get, isInvalidTokenError, sleep } from "$lib/utils";
import { redirect } from "@sveltejs/kit";

export const load = async ({ cookies, request, url }) => {
	const { host, pathname } = url;
	let user;
	const token = cookies.get("token");
	if (token) {
		try {
			user = await get("/me", auth(cookies));
		} catch (e) {
			const { message } = e as Error;
			if (message.startsWith("Rate")) {
				await sleep(3000);
				try {
					user = await get("/me", auth(cookies));
				} catch (retryError) {
					if (isInvalidTokenError(retryError) && pathname !== "/logout") {
						redirect(307, "/logout");
					}
					throw retryError;
				}
			} else if (isInvalidTokenError(e) && pathname !== "/logout") {
				redirect(307, "/logout");
			} else {
				throw e;
			}
		}
	}

	// Try to get the locale from cookie
	let locale = user?.language || (cookies.get("lang") || "").toLowerCase();

	// Get user preferred locale
	if (!locale) {
		locale = `${`${request.headers.get("accept-language")}`.match(
			/[a-zA-Z]+?(?=-|_|,|;)/,
		)}`.toLowerCase();
	}

	// Get defined locales
	const supportedLocales = locales.get().map((l) => l.toLowerCase());

	// Use default locale if current locale is not supported
	if (!supportedLocales.includes(locale)) {
		locale = defaultLocale;
	}

	await loadTranslations(locale, pathname); // keep this just before the `return`

	const theme = cookies.get("theme") || "light";

	return {
		theme,
		host,
		pathname,
		i18n: { locale, route: pathname },
		user,
	};
};