From f4eb8b6fc931f7ded138dceb2b9df4c63ac7e353 Mon Sep 17 00:00:00 2001 From: Joe Carstairs <65492573+Sycamost@users.noreply.github.com> Date: Sat, 26 Aug 2023 16:58:27 +0100 Subject: Differentiates getLocaleFromPath failure strategies --- src/lib/getLocaleFromPath.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) (limited to 'src/lib/getLocaleFromPath.ts') 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; +} -- cgit v1.2.3