diff options
Diffstat (limited to 'src/lib')
| -rw-r--r-- | src/lib/getLocaleFromPath.ts | 18 |
1 files changed, 15 insertions, 3 deletions
diff --git a/src/lib/getLocaleFromPath.ts b/src/lib/getLocaleFromPath.ts index f5dc697..2cfaf41 100644 --- a/src/lib/getLocaleFromPath.ts +++ b/src/lib/getLocaleFromPath.ts @@ -1,11 +1,23 @@ -import locales from '$i18n/locales'; +import locales, { defaultLocale } from '$i18n/locales'; import type Locale from '$types/Locale'; -export default function (path: string): Locale { +export function getLocaleFromPath(path: string): Locale | null { const regex = new RegExp(`^/(${locales.join('|')})`); const match = path.match(regex)?.[1]; if (!match) { - throw new Error(`Cannot find locale in path ${path}.`); + return null; } return match as Locale; } + +export function getLocaleFromPathOrDefault(path: string): Locale { + return getLocaleFromPath(path) ?? defaultLocale; +} + +export function getLocaleFromPathOrThrow(path: string): Locale { + const locale = getLocaleFromPath(path); + if (!locale) { + throw new Error(`Cannot find locale in path ${path}.`); + } + return locale; +} |
