All files / lib/services i18n.service.ts

95.92% Statements 47/49
85% Branches 34/40
100% Functions 6/6
95.74% Lines 45/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 1345x 5x 5x                   5x 5x 5x               5x     12x   12x   12x 12x 12x   12x   12x             172x         172x 172x   172x         172x   172x       172x         6x 2x 2x   2x             170x       170x 3x         170x       16x       181x       6x 6x         6x     6x 6x     6x         172x 172x 52x       52x 130x 52x 52x       172x      
import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
import * as format from 'string-format';
import {
  I18N_OPTIONS,
  I18N_TRANSLATIONS,
  I18N_LANGUAGES,
  I18N_LANGUAGES_SUBJECT,
  I18N_TRANSLATIONS_SUBJECT,
} from '../i18n.constants';
import { I18nOptions } from '..';
import { I18nTranslation } from '../interfaces/i18n-translation.interface';
import * as _ from 'lodash';
import { Observable, BehaviorSubject } from 'rxjs';
import { I18nParser } from '../parsers/i18n.parser';
import { take } from 'rxjs/operators';
 
export type translateOptions = {
  lang?: string;
  args?: ({ [k: string]: any } | string)[] | { [k: string]: any };
};
 
@Injectable()
export class I18nService {
  constructor(
    @Inject(I18N_OPTIONS)
    private readonly i18nOptions: I18nOptions,
    @Inject(I18N_TRANSLATIONS)
    private readonly translations: Observable<I18nTranslation>,
    @Inject(I18N_LANGUAGES)
    private readonly supportedLanguages: Observable<string[]>,
    private readonly logger: Logger,
    private readonly parser: I18nParser,
    @Inject(I18N_LANGUAGES_SUBJECT)
    private readonly languagesSubject: BehaviorSubject<string[]>,
    @Inject(I18N_TRANSLATIONS_SUBJECT)
    private readonly translationsSubject: BehaviorSubject<I18nTranslation>,
  ) {}
 
  public async translate(
    key: string,
    options?: translateOptions,
  ): Promise<string> {
    options = {
      lang: this.i18nOptions.fallbackLanguage,
      ...options,
    };
 
    const { args } = options;
    let { lang } = options;
 
    lang =
      lang === undefined || lang === null
        ? this.i18nOptions.fallbackLanguage
        : lang;
 
    lang = await this.handleFallbacks(lang);
 
    const translationsByLanguage = (
      await this.translations.pipe(take(1)).toPromise()
    )[lang];
 
    if (
      translationsByLanguage === undefined ||
      translationsByLanguage === null ||
      (!!translationsByLanguage && !translationsByLanguage.hasOwnProperty(key))
    ) {
      if (lang !== this.i18nOptions.fallbackLanguage) {
        const message = `Translation "${key}" in "${lang}" does not exist.`;
        this.logger.error(message);
 
        return this.translate(key, {
          lang: this.i18nOptions.fallbackLanguage,
          args,
        });
      }
    }
 
    let translation = translationsByLanguage
      ? translationsByLanguage[key]
      : key;
 
    if (translation && (args || (args instanceof Array && args.length > 0))) {
      translation = format(
        translation,
        ...(args instanceof Array ? args || [] : [args]),
      );
    }
    return translation || key;
  }
 
  public t(key: string, options?: translateOptions) {
    return this.translate(key, options);
  }
 
  public async getSupportedLanguages() {
    return this.supportedLanguages.pipe(take(1)).toPromise();
  }
 
  public async refresh() {
    const translations = await this.parser.parse();
    Iif (translations instanceof Observable) {
      this.translationsSubject.next(
        await translations.pipe(take(1)).toPromise(),
      );
    } else {
      this.translationsSubject.next(translations);
    }
 
    const languages = await this.parser.languages();
    Iif (languages instanceof Observable) {
      this.languagesSubject.next(await languages.pipe(take(1)).toPromise());
    } else {
      this.languagesSubject.next(languages);
    }
  }
 
  private async handleFallbacks(lang: string) {
    const supportedLanguages = await this.getSupportedLanguages();
    if (this.i18nOptions.fallbacks && !supportedLanguages.includes(lang)) {
      const sanitizedLang = lang.includes('-')
        ? lang.substring(0, lang.indexOf('-')).concat('-*')
        : lang;
 
      for (const key in this.i18nOptions.fallbacks) {
        if (key === lang || key === sanitizedLang) {
          lang = this.i18nOptions.fallbacks[key];
          break;
        }
      }
    }
    return lang;
  }
}