All files / src/use-cases/translate-locales TranslateLocales.ts

15.38% Statements 4/26
0% Branches 0/10
33.33% Functions 1/3
15.38% Lines 4/26
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  1x     1x 1x                                                                           1x                        
import { UseCase } from './../UseCase';
import { Command } from './Command';
import { Responder } from './Responder';
import { FileSystemService } from './../../services/file-system/FileSystemService';
import { TranslationService } from './../../services/translation/TranslationService';
 
 
export class TranslateLocales implements UseCase {

  constructor(
    private fsService: FileSystemService,
    private tService: TranslationService) {}
 
  async execute(command: Command, responder: Responder): Promise<void> {
    let baseLocale: any = null;

    if (command.sourceLng === command.targetLng) {
      responder.cannotTranslateLocales(new Error('Source and target language is the same!'));
      return;
    }
 
    if (!this.validateLocaleCode(command.sourceLng) || 
      !this.validateLocaleCode(command.targetLng)) {
      responder.cannotTranslateLocales(
        new Error(`Invalid locale code - use two letters, eg. 'en' or 'es'.`)
      );
      return;
    }
 
    try {
      baseLocale = await this.fsService.getFileContentAsObj(command.baseLocalePath);
    } catch(e) {
      responder.cannotTranslateLocales(e);
      return;
    }

    let translated = null;
    try {
      translated = await this.tService.translate(
        command.sourceLng, command.targetLng, baseLocale, command.overrideExisting
      );
    } catch(e) {
      responder.cannotTranslateLocales(e);
      return;
    }
 
    responder.localesTranslated(baseLocale, translated);
  }
 
  validateLocaleCode(locale: string) {
    if (locale.length === 0) return false;
    if (locale.length > 4) return false;
    return true;
  }
}