All files / src/components/app/services IntlProvider.ts

11.11% Statements 2/18
0% Branches 0/8
0% Functions 0/3
11.11% Lines 2/18

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 594x   4x                                                                                                                
import Observer from "../../../utils/observer/Observer";
 
export default class IntlProvider extends Observer {
 
	constructor(
 
		/**
		 * The current language set in the provider
		 */
		public lang: string,
 
		/**
		 * The data with the translation
		 */
		public data: any
	) {
		super('handleLanguageChanged');
	}
 
	setLanguage(lang: string) {
 
		if (this.lang !== lang) {
 
			this.lang = lang;
 
			this.notify();
		}
	}
 
	/**
	 * Retrieves the translated text or returns a string with the key value if the translation was not found
	 */
	getTranslation(lang: string | undefined, key: string): string {
 
		// If the lang is not provided use the current language of the provider
		const lng = lang || this.lang;
 
		const data = this.data[lng];
 
		if (data === undefined) { // There are no translations for this language
 
			console.error(`There are no translations for language: [${lng}]. (key was [${key}]).`);
 
			return undefined;
		}
 
		const translation = data[key];
 
		if (translation === undefined) { // There is no translation for this key in this language
		
			console.error(`Missing translation for key: [${key}] in language: [${lng}].`);
 
			return undefined;
		}
 
		return translation;
	}
}