From 084c85368e1d11dfced6e246a5417377b3402f5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcos=20Susa=C3=B1a?= Date: Sat, 10 Aug 2024 20:13:02 -0400 Subject: [PATCH] feat: reload langs --- src/langs/handler.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/langs/handler.ts b/src/langs/handler.ts index 27fe977..d5c9720 100644 --- a/src/langs/handler.ts +++ b/src/langs/handler.ts @@ -1,10 +1,11 @@ -import { BaseHandler } from '../common'; +import { BaseHandler, isCloudfareWorker, magicImport } from '../common'; import { LangRouter } from './router'; import type { FileLoaded } from '../commands/handler'; import type { LocaleString, Locale } from '../types'; export class LangsHandler extends BaseHandler { values: Partial> = {}; + private __paths: Partial> = {}; protected filter = (path: string) => path.endsWith('.js') || (!path.endsWith('.d.ts') && path.endsWith('.ts')) || path.endsWith('.json'); defaultLang?: string; @@ -47,6 +48,7 @@ export class LangsHandler extends BaseHandler { parse(file: EventInstance) { const locale = file.name.split('.').slice(0, -1).join('.') || file.name; const result = this.onFile(locale, file.file); + if ('path' in file) this.__paths[locale] = file.path as string; if (result) this.values[locale] = result; } @@ -56,6 +58,27 @@ export class LangsHandler extends BaseHandler { } } + async reload(lang: string) { + if (isCloudfareWorker()) { + throw new Error('Reload in cloudfare worker is not supported'); + } + const value = this.__paths[lang]; + if (!value) return null; + delete require.cache[value]; + + return (this.values[lang] = await magicImport(value).then(x => this.onFile(lang, x))); + } + + async reloadAll(stopIfFail = true) { + for (const i in this.__paths) { + try { + await this.reload(i); + } catch (e) { + if (stopIfFail) throw e; + } + } + } + onFile(_locale: string, file: FileLoaded>): Record | false { return file.default ?? false; }