Total Complexity | 6 |
Complexity/F | 1.2 |
Lines of Code | 47 |
Function Count | 5 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | import path from 'path'; |
||
2 | import fs from 'fs'; |
||
3 | import { promisify, resolve } from 'bluebird'; |
||
4 | import osLocale from 'os-locale'; |
||
5 | import { curry, propOr, replace } from 'ramda'; |
||
6 | |||
7 | const readFile = promisify(fs.readFile); |
||
8 | |||
9 | /** |
||
10 | * Returns the user locale. Firstly consider the env variable and, if it |
||
11 | * doesn't exist, consider machine's locale |
||
12 | * |
||
13 | * @return {Promise} |
||
14 | */ |
||
15 | export function getLocale() { |
||
16 | const { RUNG_LOCALE } = process.env; |
||
17 | return resolve(RUNG_LOCALE ? RUNG_LOCALE : osLocale()); |
||
18 | } |
||
19 | |||
20 | /** |
||
21 | * Translates a string or fallback to the key |
||
22 | * |
||
23 | * @param {Object} map - Object containing app strings |
||
24 | * @param {String} key - Key to search in hashmap |
||
25 | * @return {String} |
||
26 | */ |
||
27 | export const translator = curry((map, key, params = {}) => { |
||
28 | const sentence = propOr(key, key, map); |
||
29 | |||
30 | return replace( |
||
31 | /{{(\w+)}}/g, |
||
32 | (full, partial) => params[partial] || full, |
||
33 | sentence |
||
34 | ); |
||
35 | }); |
||
36 | |||
37 | /** |
||
38 | * Reads the JSON file corresponding to a specific locale |
||
39 | * |
||
40 | * @return {Promise} |
||
41 | */ |
||
42 | export function getLocaleStrings() { |
||
43 | return getLocale() |
||
44 | .then(locale => readFile(path.join('locales', `${locale}.json`))) |
||
45 | .then(JSON.parse) |
||
46 | .catchReturn({}); |
||
47 | } |
||
48 |