-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.ts
52 lines (46 loc) · 1.47 KB
/
index.ts
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
const i18nRedirectsUtil = ({
path,
defaultLocale,
availableLocales,
cookieLocale,
acceptedLanguages,
autoRedirectByLocale
}: {
path: string;
defaultLocale: string;
cookieLocale: string;
availableLocales: string[];
acceptedLanguages: string[];
autoRedirectByLocale: boolean;
}): {
getRedirectPath: () => string;
getTargetLocale: () => string;
} => {
const localeRegexp = new RegExp(`^/(?<locale>${availableLocales.join('|')})(?=(/|$))`, 'g');
const localeFromPath = localeRegexp.exec(path)?.groups.locale;
const strippedLocaleFromPath = path.replace(`/${localeFromPath}`, '');
const removeTailingSlash = (path: string): string => path.replace(/\/$/, '');
const getTargetLocale = (): string => {
const languagesOrderedByPriority = [
localeFromPath,
...(autoRedirectByLocale && [cookieLocale]),
...(autoRedirectByLocale && acceptedLanguages),
defaultLocale
];
return languagesOrderedByPriority.find(code => availableLocales.includes(code));
};
const getRedirectPath = (): string => {
const targetLocale = getTargetLocale();
const isTargetDefaultLocale = targetLocale === defaultLocale;
const isTargetInPath = targetLocale === localeFromPath;
if (!localeFromPath && !isTargetInPath && !isTargetDefaultLocale) {
return removeTailingSlash(`/${targetLocale}${strippedLocaleFromPath}`);
}
return '';
};
return {
getRedirectPath,
getTargetLocale
};
};
export default i18nRedirectsUtil;