-
Notifications
You must be signed in to change notification settings - Fork 13
/
Translation.ts
59 lines (49 loc) 路 1.56 KB
/
Translation.ts
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
59
import { env, utils } from 'decentraland-commons'
import * as flat from 'flat'
import * as fs from 'fs'
import * as path from 'path'
export interface TranslationData {
[key: string]: string
}
export interface TranslationCache {
locale?: TranslationData
}
export class Translation {
static DEFAULT_LOCALE = 'en'
localesPath: string
cache: TranslationCache
constructor() {
this.localesPath = env.get(
'LOCALES_PATH',
path.resolve(__dirname, './locales')
)
this.cache = {} // {locale: translations}
}
async fetch(locale: string): Promise<TranslationData> {
if (!this.cache[locale]) {
const availableLocales = await this.getAvailableLocales()
if (availableLocales.includes(locale)) {
this.cache[locale] = this.parse(await this.readFile(locale))
}
}
return this.cache[locale] || {}
}
async getAvailableLocales(): Promise<string[]> {
const files = await utils.promisify<string[]>(fs.readdir)(this.localesPath)
return files.map(filePath =>
path.basename(filePath, path.extname(filePath))
)
}
parse(fileContents: string): TranslationData {
// The translation lib ( https://github.com/yahoo/react-intl ) doesn't support nested values
// So instead we flatten the structure to look like `{ 'nested.prop': 'value' }`
const translations = JSON.parse(fileContents)
return flat.flatten(translations)
}
async readFile(locale: string): Promise<string> {
return utils.promisify<string>(fs.readFile)(
path.resolve(this.localesPath, `${locale}.json`),
'utf8'
)
}
}