Total Complexity | 8 |
Complexity/F | 1.33 |
Lines of Code | 50 |
Function Count | 6 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
1 | import { sprintf } from 'sprintf-js'; |
||
2 | import fetch from 'node-fetch'; |
||
3 | |||
4 | class Bawler { |
||
5 | constructor() { |
||
6 | this.messages = {}; |
||
7 | this.currentLang = 'en'; |
||
8 | } |
||
9 | |||
10 | lang(lang = 'en') { |
||
11 | this.currentLang = lang; |
||
12 | } |
||
13 | |||
14 | register(lang, messages) { |
||
15 | this.messages[lang] = messages; |
||
16 | } |
||
17 | |||
18 | async registerUrl(url, lang) { |
||
19 | const data = await fetch(url); |
||
20 | const jsondata = await data.json(); |
||
21 | |||
22 | this.register(lang, jsondata); |
||
23 | } |
||
24 | |||
25 | all(lang = null) { |
||
26 | if (!lang) { |
||
27 | return this.messages; |
||
28 | } |
||
29 | |||
30 | return this.messages[lang] || {}; |
||
31 | } |
||
32 | |||
33 | msg(messageKey, vars = []) { |
||
34 | const message = this.all(this.currentLang)[messageKey] || messageKey; |
||
35 | const args = [message, ...vars]; |
||
36 | |||
37 | return sprintf(...args); |
||
38 | } |
||
39 | } |
||
40 | |||
41 | const instance = new Bawler(); |
||
42 | const msg = instance.msg.bind(instance); |
||
43 | const lang = instance.lang.bind(instance); |
||
44 | const register = instance.register.bind(instance); |
||
45 | const registerUrl = instance.registerUrl.bind(instance); |
||
46 | const all = instance.all.bind(instance); |
||
47 | |||
48 | export default instance; |
||
49 | |||
50 | export { msg, lang, register, registerUrl, all }; |
||
51 |