aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/+layout.server.ts
blob: 584e836c0c469429f16fd9ad72f39fd584a86369 (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
import {
	defaultLocale,
	loadTranslations,
	locales,
} from "$lib/translations/index";
import { auth, get, sleep } from "$lib/utils";

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) {
			if (e.message.startsWith("Rate")) await sleep(3000);
			user = await get("/me", auth(cookies));
		}
	}

	// 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,
	};
};