-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi18n.ts
More file actions
49 lines (43 loc) · 1.62 KB
/
i18n.ts
File metadata and controls
49 lines (43 loc) · 1.62 KB
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
import esData from '../../i18n/es.json' with { type: 'json' };
import enData from '../../i18n/en.json' with { type: 'json' };
const translations: Record<string, Record<string, unknown>> = {
es: esData as Record<string, unknown>,
en: enData as Record<string, unknown>,
};
function resolveKey(obj: Record<string, unknown>, key: string): unknown {
const parts = key.split('.');
let current: unknown = obj;
for (const part of parts) {
if (current && typeof current === 'object' && part in current) {
current = (current as Record<string, unknown>)[part];
} else {
return key;
}
}
return current;
}
export function t(key: string, locale: string = 'es'): string {
const data = translations[locale] || translations.es;
const result = resolveKey(data, key);
return typeof result === 'string' ? result : key;
}
export function tArr(key: string, locale: string = 'es'): string[] {
const data = translations[locale] || translations.es;
const result = resolveKey(data, key);
if (typeof result === 'object' && result !== null) {
return Object.values(result as Record<string, unknown>)
.filter((v): v is string => typeof v === 'string');
}
return [];
}
export function tObj<T = Record<string, unknown>>(key: string, locale: string = 'es'): T {
const data = translations[locale] || translations.es;
const result = resolveKey(data, key);
if (typeof result === 'object' && result !== null) return result as T;
return {} as T;
}
export function getLocale(queryParams: URLSearchParams): string {
const lang = queryParams.get('lang');
if (lang === 'en' || lang === 'es') return lang;
return 'es';
}