diff options
Diffstat (limited to 'src/utils/helpers/i18n.ts')
| -rw-r--r-- | src/utils/helpers/i18n.ts | 23 |
1 files changed, 22 insertions, 1 deletions
diff --git a/src/utils/helpers/i18n.ts b/src/utils/helpers/i18n.ts index dd010c4..16c83f4 100644 --- a/src/utils/helpers/i18n.ts +++ b/src/utils/helpers/i18n.ts @@ -1,18 +1,22 @@ import { config } from '@config/website'; +import { createIntl, createIntlCache, IntlShape } from '@formatjs/intl'; import { readFile } from 'fs/promises'; import path from 'path'; type Messages = { [key: string]: string }; +export const defaultLocale = config.locales.defaultLocale; + /** * Load the translation for the provided locale. + * * @param currentLocale - The current locale. * @returns {Promise<Messages>} The translated strings. */ export async function loadTranslation( currentLocale: string | undefined ): Promise<Messages> { - const locale: string = currentLocale || config.locales.defaultLocale; + const locale: string = currentLocale || defaultLocale; const languagePath = path.join(process.cwd(), `lang/${locale}.json`); @@ -26,3 +30,20 @@ export async function loadTranslation( throw error; } } + +/** + * Create an Intl object to be used outside components. + * + * @returns {<Promise<IntlShape<string>>} The Intl object. + */ +export async function getIntlInstance(): Promise<IntlShape<string>> { + try { + const cache = createIntlCache(); + const messages = await loadTranslation(defaultLocale); + + return createIntl({ locale: defaultLocale, messages }, cache); + } catch (error) { + console.error('Error: Could not create an Intl instance.'); + throw error; + } +} |
