src/Infrastructure/Adapter/FluentTranslatorAdapter.ts   A
last analyzed

Complexity

Total Complexity 4
Complexity/F 4

Size

Lines of Code 57
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 48
mnd 3
bc 3
fnc 1
dl 0
loc 57
bpm 3
cpm 4
noi 0
c 0
b 0
f 0
rs 10

1 Function

Rating   Name   Duplication   Size   Complexity  
A FluentTranslatorAdapter.translate 0 8 2
1
import * as fs from 'fs';
2
import { Injectable } from '@nestjs/common';
3
import { ConfigService } from '@nestjs/config';
4
import * as fluent from '@fluent/bundle';
5
import { ITranslator } from 'src/Infrastructure/Translations/ITranslator';
6
7
@Injectable()
8
export class FluentTranslatorAdapter implements ITranslator {
9
  private path: string;
10
  private locale: string;
11
  private bundle: fluent.FluentBundle = null;
12
13
  constructor(private readonly configService: ConfigService) {
14
    this.path = this.configService.get<string>('FLUENT_PATH');
15
    this.locale = this.configService.get<string>('FLUENT_LOCALE');
16
    this.bundle = _readBundle(this.path, this.locale);
17
  }
18
19
  public translate(key: string, params: Record<string, any> = {}): string {
20
    if (process.env.NODE_ENV !== 'production') {
21
      // Refresh during development
22
      this.bundle = _readBundle(this.path, this.locale);
23
    }
24
25
    return _translate(this.bundle, key, params);
26
  }
27
}
28
29
const _readBundle = (path: string, locale: string) => {
30
  const content = fs.readFileSync(path).toString();
31
32
  const resource = new fluent.FluentResource(content);
33
34
  const bundle = new fluent.FluentBundle(locale, { useIsolating: false });
35
  const errors = bundle.addResource(resource);
36
37
  if (errors.length > 0) {
38
    throw errors[0];
39
  }
40
41
  return bundle;
42
};
43
44
const _translate = (
45
  bundle: fluent.FluentBundle,
46
  key: string,
47
  params: Record<string, any> = {}
48
): string | null => {
49
  const message = bundle.getMessage(key);
50
51
  if (!message || !message.value) {
52
    return key;
53
  }
54
55
  return bundle.formatPattern(message.value, params);
56
};
57