UNPKG

@ngx-easy-i18n-js/http-loader

Version:
95 lines (89 loc) 3.25 kB
import { EasyI18nLoader, EasyI18nService } from '@ngx-easy-i18n-js/core'; import { HttpClient } from '@angular/common/http'; import { forkJoin, catchError, of, from } from 'rxjs'; import * as lodash from 'lodash'; import { map } from 'rxjs/operators'; import { inject } from '@angular/core'; class HttpEasyI18nLoader extends EasyI18nLoader { constructor(httpClient, options) { super(); this.httpClient = httpClient; this.options = { prefix: '/assets/i18n/', suffix: '.json', ...(options ?? {}) }; } /** * Return messages with locale with HttpClient `${this.options.prefix ?? ''}${locale}${this.options.suffix ?? ''}` * @param locale */ getMessages(locale) { const prefix = lodash.isArray(this.options.prefix) ? this.options.prefix : [this.options.prefix]; return forkJoin(prefix.map(p => { const url = `${p ?? ''}${locale}${this.options.suffix ?? ''}`; return this.httpClient.get(url).pipe(catchError((err) => { console.error(`Failed to load file ${url}`, err); return of({}); })); })).pipe(map(res => lodash.defaultsDeep({}, ...lodash.compact(res)))); } } class ScopedHttpEasyI18nLoader extends EasyI18nLoader { constructor(httpClient, scopes, options) { super(); this.httpClient = httpClient; this.scopes = scopes; this.options = options; this.list = scopes.map(s => ({ loader: new HttpEasyI18nLoader(httpClient, { prefix: s.prefix, suffix: options?.suffix ?? '.json' }), scope: s.scope ?? '' })); } getMessages(locale) { return forkJoin(this.list.map(l => l.loader.getMessages(locale).pipe(map(res => { if (!l.scope) { return res; } return lodash.set({}, l.scope, res); })))).pipe(map(datas => lodash.defaultsDeep({}, ...lodash.compact(datas)))); } } function appendScopedHttpEasyI18nLoader(scopes, options) { let alreadyAppened = false; return () => { if (alreadyAppened) { return true; } alreadyAppened = true; const httpClient = inject(HttpClient); const easyI18nService = inject(EasyI18nService); return from(easyI18nService.appendLoader(new ScopedHttpEasyI18nLoader(httpClient, scopes, options))).pipe(map(() => true)); }; } function provideEasyI18nLoader(options) { return [ { provide: EasyI18nLoader, deps: [HttpClient], useFactory: (httpClient) => new HttpEasyI18nLoader(httpClient, options) } ]; } function provideEasyI18nScopedLoader(scopes, options) { return [ { provide: EasyI18nLoader, deps: [HttpClient], useFactory: (httpClient) => new ScopedHttpEasyI18nLoader(httpClient, scopes, options) } ]; } /** * Generated bundle index. Do not edit. */ export { HttpEasyI18nLoader, ScopedHttpEasyI18nLoader, appendScopedHttpEasyI18nLoader, provideEasyI18nLoader, provideEasyI18nScopedLoader }; //# sourceMappingURL=ngx-easy-i18n-js-http-loader.mjs.map