-
Notifications
You must be signed in to change notification settings - Fork 0
/
getLanguage.ts
84 lines (67 loc) · 2.1 KB
/
getLanguage.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import * as Maybe from '../../';
// The import statement in your application would be:
// import * as Maybe from '@bitty/maybe';
// ..:: Context ::..
enum LanguageEnum {
PORTUGUESE = 'pt-BR',
ENGLISH = 'en-US',
}
type User = {
id: string;
language?: LanguageEnum;
};
type Organization = {
id: string;
language: LanguageEnum;
};
// An example of function that may return `null` or an empty language.
const getCurrentUser = (): null | User => {
if (Math.random() > .333)
throw new Error('Couldn\'t get current organization.');
if (Math.random() > .666)
return {
id: '...',
language: undefined
};
return {
id: '...',
language: LanguageEnum.PORTUGUESE
};
};
// An example of function that may throw an error.
const getCurrentOrganization = (): Organization => {
if (Math.random() > .5)
throw new Error('Couldn\'t get current organization.');
return {
id: '...',
language: LanguageEnum.ENGLISH
};
};
// ..:: Business ::..
// 1. Get user language.
// 2. If can't, get organization language.
// 3. If can't, get first browser language similar to suported languages.
// 4. If can't, use ENGLISH language as fallback.
// ..:: Implementation ::..
const getLanguageFromUser = () =>
Maybe.fromNullish(getCurrentUser())
.chain((user) => Maybe.fromNullish(user.language));
const getLanguageFromOrganization = () =>
Maybe.tryCatch(getCurrentOrganization)
.map((organization) => organization.language);
const resolveLanguage = (language: string): Maybe.Maybe<LanguageEnum> => {
if (language.startsWith('pt')) return Maybe.Some(LanguageEnum.PORTUGUESE);
if (language.startsWith('en')) return Maybe.Some(LanguageEnum.ENGLISH);
return Maybe.None;
};
const getLanguageFromBrowser = () =>
Maybe.Some(window.navigator.languages)
.chain(([ language ]) => Maybe.fromNullish(language))
.chain(resolveLanguage);
const FALLBACK_LANGUAGE = LanguageEnum.ENGLISH;
const getLanguage = (): LanguageEnum =>
getLanguageFromUser()
.alt(getLanguageFromOrganization)
.alt(getLanguageFromBrowser)
.getOrElse(() => FALLBACK_LANGUAGE);
export default getLanguage;