52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
import type { Locale } from '@intlify/core-base';
|
|
|
|
export const useI18nKey = () => {
|
|
const { locale, locales } = useI18n();
|
|
|
|
function tKey<K extends string>(
|
|
obj: Record<`${K}_${Locale}`, string>,
|
|
key: K
|
|
) {
|
|
return computed(() => obj[`${key}_${locale.value}`]);
|
|
}
|
|
|
|
function tSluggy(
|
|
obj: { id: number | string } & (
|
|
| Record<`name_${Locale}`, string | null | undefined>
|
|
| Record<`title_${Locale}`, string | null | undefined>
|
|
)
|
|
) {
|
|
return computed(() =>
|
|
sluggy({
|
|
id: obj.id,
|
|
title: hasKey(obj, 'title') ? tKey(obj, 'title').value : undefined,
|
|
name: hasKey(obj, 'name') ? tKey(obj, 'name').value : undefined
|
|
})
|
|
);
|
|
}
|
|
|
|
function hasKey<K extends string>(
|
|
obj:
|
|
| Record<`${K}_${Locale}`, string | null | undefined>
|
|
| null
|
|
| undefined
|
|
| object,
|
|
key: K
|
|
): obj is Record<`${K}_${Locale}`, string> {
|
|
return (
|
|
!!obj &&
|
|
locales.value.every(
|
|
(l) =>
|
|
typeof obj === 'object' &&
|
|
Object.prototype.hasOwnProperty.call(obj, `${key}_${l.code}`) &&
|
|
// @ts-expect-error this is a type check
|
|
typeof obj[`${key}_${l.code}`] === 'string' &&
|
|
// @ts-expect-error this is a type check
|
|
obj[`${key}_${l.code}`]
|
|
)
|
|
);
|
|
}
|
|
|
|
return { tKey, hasKey, tSluggy };
|
|
};
|