All files / src/app/core/services/localizations localizations.service.ts

87.5% Statements 21/24
73.33% Branches 11/15
66.66% Functions 6/9
86.95% Lines 20/23

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 64103x 103x 103x 103x 103x   103x 103x         2x 2x 4x 4x     2x       103x     4x 4x                     3x   3x             2x   1x 1x                            
import { HttpClient } from '@angular/common/http';
import { ErrorHandler, Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable, of } from 'rxjs';
import { catchError, concatMap, map, take } from 'rxjs/operators';
 
import { getRestEndpoint } from 'ish-core/store/core/configuration';
import { whenTruthy } from 'ish-core/utils/operators';
import { Translations } from 'ish-core/utils/translate/translations.type';
 
function filterAndTransformKeys(translations: Record<string, string>, prefix = 'pwa-'): Translations {
  // this implementation is mutable by intention, as it can lead to performance issues when using Object.entries and reduce
  const filtered: Record<string, string> = {};
  for (const key in translations) {
    if (key.startsWith(prefix)) {
      filtered[key.substring(prefix.length)] = translations[key];
    }
  }
  return filtered;
}
 
@Injectable({ providedIn: 'root' })
export class LocalizationsService {
  private icmEndpoint$: Observable<string>;
 
  constructor(private httpClient: HttpClient, private errorHandler: ErrorHandler, store: Store) {
    this.icmEndpoint$ = store.pipe(select(getRestEndpoint), whenTruthy(), take(1));
  }
 
  /**
   * Retrieves server-side translations for a specified language and key prefix.
   *
   * @param lang - The language code for which translations are requested.
   * @param prefix - The prefix used to filter translation keys. Defaults to 'pwa-'.
   * @returns An Observable emitting a record of filtered and transformed translation key-value pairs.
   */
  getServerTranslations(lang: string, prefix = 'pwa-') {
    return this.icmEndpoint$.pipe(
      concatMap(url =>
        this.httpClient
          .get<Record<string, string>>(`${url};loc=${lang}/localizations`, {
            params: {
              searchKeys: prefix,
            },
          })
          .pipe(
            map(translations => filterAndTransformKeys(translations, prefix)),
            catchError(err => {
              this.errorHandler.handleError(err);
              return of({});
            })
          )
      )
    );
  }
 
  getSpecificTranslation(lang: string, key: string) {
    return this.icmEndpoint$.pipe(
      concatMap(url => this.httpClient.get(`${url};loc=${lang}/localizations/${key}`, { responseType: 'text' })),
      catchError(() => of(''))
    );
  }
}