diff options
| author | Joe Carstairs <65492573+Sycamost@users.noreply.github.com> | 2023-08-26 16:58:27 +0100 |
|---|---|---|
| committer | Joe Carstairs <65492573+Sycamost@users.noreply.github.com> | 2023-08-26 16:58:27 +0100 |
| commit | f4eb8b6fc931f7ded138dceb2b9df4c63ac7e353 (patch) | |
| tree | ca189d7ff7beb80a2626c0747a367e745374cf78 /src/lib/getLocaleFromPath.ts | |
| parent | c8f9f07197fa49ad114a30d4c40bdf24443acc3a (diff) | |
Differentiates getLocaleFromPath failure strategies
Diffstat (limited to 'src/lib/getLocaleFromPath.ts')
| -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; +} |
