From 26463bfde7e03b0b99b7909216ead14b45134744 Mon Sep 17 00:00:00 2001 From: Alex Komz Date: Sat, 20 Jan 2024 15:18:27 +0300 Subject: [PATCH] feat(settings): adds a script to automatically update locales --- scripts/updateLocales.js | 81 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 scripts/updateLocales.js diff --git a/scripts/updateLocales.js b/scripts/updateLocales.js new file mode 100644 index 0000000..93db77f --- /dev/null +++ b/scripts/updateLocales.js @@ -0,0 +1,81 @@ +/** + * Fetches and writes to the locale file from github dayjs + * node.js >= 20 lts + * @module Locale + * */ + +const fs = require('node:fs/promises'); + +const LOCALES_PATH = 'src/settings/locales.ts'; +const GITHUB_LOCALES_URL = 'https://github.com/iamkun/dayjs/tree/dev/src/locale'; + +const fetchLocalesList = async (githubUrl) => { + try { + const res = await fetch(githubUrl); + const json = await res.json(); + const {items} = json.payload.tree; + + return items.map((item) => item.name); + } catch (error) { + throw new Error( + `Something went wrong when trying to retrieve data from github dayjs, check if the URL is correct ${GITHUB_LOCALES_URL}`, + ); + } +}; + +const createLocaleFile = async (localesPath) => { + if (require('node:fs').existsSync(localesPath)) { + await fs.rm(localesPath); + } + + return await fs.open(localesPath, 'w'); +}; + +(async function () { + try { + const localesList = await fetchLocalesList(GITHUB_LOCALES_URL); + + console.log('Locales loaded successfully'); + + const localeFile = await createLocaleFile(LOCALES_PATH); + + console.log(`File "${LOCALES_PATH}" created successfully`); + + const localeLoaderType = + "type LocaleLoader = () => Promise;\n\n"; + + await localeFile.appendFile(localeLoaderType); + await localeFile.appendFile('const localeLoaders: Record = '); + await localeFile.appendFile('{\n'); + + await Promise.allSettled( + localesList.map(async (locale) => { + if (locale === '' || locale === undefined || locale === null) return; + + const localeName = locale.substring(0, locale.lastIndexOf('.')); + const localeModulesObjectPart = ` "${localeName}": () => import('dayjs/locale/${locale}'),\n`; + + await localeFile.appendFile(localeModulesObjectPart); + + console.log(`Locale "${localeName}" written successfully`); + }), + ); + + await localeFile.appendFile('};\n\n'); + + const interfaceFunction = + 'export const getLocaleLoader = (locale: string): LocaleLoader => {\n' + + ' const loader: LocaleLoader | undefined = localeLoaders[locale];\n' + + '\n' + + " if (typeof loader === 'function') return loader;\n" + + '\n' + + ' throw new Error();\n' + + '};'; + + await localeFile.appendFile(interfaceFunction); + + console.log(`Object "localeLoaders" written in file "${LOCALES_PATH}" successfully`); + } catch (error) { + console.error(error); + } +})();