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
|
|
|
|