rojects/source/locales/LocaleManager.ts

72 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

export class LocaleManager
{
static _instance:LocaleManager;
static get $()
{
if ( ! this._instance )
{
this._instance = new LocaleManager();
}
return this._instance;
}
_currentLocale = 'en';
_cache = new Map<string, string>();
get currentLocale(): string
{
return this._currentLocale;
}
setLocale( locale: string ):void
{
this._currentLocale = locale;
}
async get( localePath:string ):Promise<string>
{
return this._loadLocale( localePath );
}
async _loadLocale( relativePath: string ): Promise<string>
{
const key = `${this._currentLocale}/${relativePath}`;
if ( this._cache.has( key ) )
{
return this._cache.get( key );
}
const res = await fetch(`/api/locales/${this._currentLocale}/${relativePath}`);
if ( ! res.ok )
{
return relativePath;
}
const ext = relativePath.split('.').pop() ?? '';
let value: string;
if ( ext === 'json' )
{
const data = await res.json() as { value: string };
value = data.value;
}
else
{
value = await res.text();
}
this._cache.set( key, value );
return value;
}
invalidateCache(): void
{
this._cache.clear();
}
}