Add Locale URL

This commit is contained in:
Restray
2022-04-02 16:15:00 +02:00
parent 741db1778b
commit d910b21185
187 changed files with 683 additions and 532 deletions

View File

@@ -6,6 +6,9 @@ import { getUserDetails, sentry } from '$lib/common';
import { version } from '$lib/common';
import cookie from 'cookie';
import { dev } from '$app/env';
import { locales } from '$lib/translations';
const routeRegex = new RegExp(/^\/[^.]*([?#].*)?$/);
export const handle = handleSession(
{
@@ -62,9 +65,45 @@ export const handle = handleSession(
expires: new Date('Thu, 01 Jan 1970 00:00:01 GMT')
})
);
} finally {
return response;
}
const { url, request } = event;
const { pathname } = url;
// If this request is a route request
if (routeRegex.test(pathname)) {
// Get defined locales
const supportedLocales = locales.get();
// Try to get locale from `pathname`.
let locale = supportedLocales.find(
(l) => `${l}`.toLowerCase() === `${pathname.match(/[^/]+?(?=\/|$)/)}`.toLowerCase()
);
// If route locale is not supported
if (!locale) {
// Get user preferred locale
locale = `${`${request.headers['accept-language']}`.match(
/[a-zA-Z]+?(?=-|_|,|;)/
)}`.toLowerCase();
// Set default locale if user preferred locale does not match
if (!supportedLocales.includes(locale)) locale = 'en';
// 301 redirect
return new Response(undefined, {
headers: { location: `/${locale}${pathname}` },
status: 301
});
}
// Add html `lang` attribute
const body = await response.text();
return new Response(`${body}`.replace(/<html.*>/, `<html lang="${locale}">`), response);
}
return response;
}
);