All files / ngx-translate si-missing-translate.service.ts

91.66% Statements 11/12
66.66% Branches 6/9
100% Functions 4/4
100% Lines 10/10

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                                  1x 17x 17x     17x       4x       5x       5x 5x 4x   1x      
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Injectable } from '@angular/core';
import {
  MissingTranslationHandler,
  MissingTranslationHandlerParams,
  TranslateDefaultParser,
  Translation
} from '@ngx-translate/core';
import { Observable } from 'rxjs';
 
/**
 * Handles missing translations by returning the default value if available.
 */
@Injectable()
export class SiMissingTranslateService implements MissingTranslationHandler {
  private readonly parser = new TranslateDefaultParser();
  private readonly defaultTranslations: Record<string, string> = {};
 
  // eslint-disable-next-line @angular-eslint/prefer-inject
  constructor(private readonly appHandler?: MissingTranslationHandler) {}
 
  /** Sets a default translation for a given key. */
  setTranslation(key: string, value: string): void {
    this.defaultTranslations[key] = value;
  }
  /** Gets the default translation for a given key. */
  getDefault(key: string): string | undefined {
    return this.defaultTranslations[key];
  }
  /** {@inheritDoc} */
  handle(params: MissingTranslationHandlerParams): Translation | Observable<Translation> {
    const translated = this.getDefault(params.key);
    if (translated !== undefined) {
      return this.parser.interpolate(translated, params.interpolateParams);
    }
    return this.appHandler?.handle(params) ?? params.key;
  }
}