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

86.95% Statements 20/23
76.92% Branches 10/13
62.5% Functions 5/8
86.36% Lines 19/22

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 5799x 99x 99x 99x 99x   99x 99x         1x 1x 2x 2x     1x       99x     3x 3x       2x   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>): 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('pwa-')) {
      filtered[key.substring(4)] = 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));
  }
 
  getServerTranslations(lang: string) {
    return this.icmEndpoint$.pipe(
      concatMap(url =>
        this.httpClient
          .get(`${url};loc=${lang}/localizations`, {
            params: {
              searchKeys: 'pwa-',
            },
          })
          .pipe(
            map(filterAndTransformKeys),
            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(''))
    );
  }
}