Browse Source

chore: refactor code

pull/2503/head
Dhoni77 2 years ago
committed by Thomas
parent
commit
8efce4f781
  1. 23
      apps/api/src/services/i18n/i18n.service.ts

23
apps/api/src/services/i18n/i18n.service.ts

@ -1,15 +1,15 @@
import * as fs from 'fs'; import { readdirSync, readFileSync, existsSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { Injectable } from '@nestjs/common'; import { Injectable, Logger } from '@nestjs/common';
import * as cheerio from 'cheerio'; import * as cheerio from 'cheerio';
@Injectable() @Injectable()
export class I18nService { export class I18nService {
private localesPath = join(__dirname, 'assets/locales/'); private localesPath = join(__dirname, 'assets', 'locales');
private localeRegex = /^messages\.[a-z]{2}\.xlf$/; private localeRegex = /^messages\.[a-z]{2}\.xlf$/;
private translations: { [locale: string]: cheerio.CheerioAPI } = {}; private translations: { [locale: string]: cheerio.CheerioAPI } = {};
constructor() { public constructor() {
this.loadFiles(); this.loadFiles();
} }
@ -37,23 +37,24 @@ export class I18nService {
private loadFiles() { private loadFiles() {
try { try {
const files = fs.readdirSync(this.localesPath, 'utf-8'); const files = readdirSync(this.localesPath, 'utf-8');
for (const file of files) { for (const file of files) {
if (!this.localeRegex.test(file)) continue; if (!this.localeRegex.test(file)) {
if (!fs.existsSync(`${this.localesPath}${file}`)) { continue;
}
if (!existsSync(join(this.localesPath, file))) {
throw new Error(`File: ${file} not found`); throw new Error(`File: ${file} not found`);
} else { } else {
const xmlData = fs.readFileSync(`${this.localesPath}${file}`, 'utf8'); const xmlData = readFileSync(join(this.localesPath, file), 'utf8');
this.translations[file.split('.')[1]] = this.parseXml(xmlData); this.translations[file.split('.')[1]] = this.parseXml(xmlData);
} }
} }
} catch (error) { } catch (error) {
console.log(error); Logger.error(error, 'I18nService');
} }
} }
private parseXml(xmlData: string): cheerio.CheerioAPI { private parseXml(xmlData: string): cheerio.CheerioAPI {
const selectorFn = cheerio.load(xmlData, { xmlMode: true }); return cheerio.load(xmlData, { xmlMode: true });
return selectorFn;
} }
} }

Loading…
Cancel
Save