summaryrefslogtreecommitdiff
path: root/src/lib/getLocaleFromPath.ts
blob: b1e815ce8ba8131c82080d42eacb92db13221b5e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import locales, { defaultLocale } from '$i18n/locales';
import type Locale from '$types/Locale';
import { correctLocaleCasing } from './correctLocaleCasing';

export function getLocaleFromPath(path: string): Locale | null {
  const regex = new RegExp(`^/(${locales.join('|')})`, 'i');
  const match = path.match(regex)?.[1];
  if (!match) {
    return null;
  }
  return correctLocaleCasing(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;
}