locale.service.ts
2.83 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import {map, catchError} from 'rxjs/operators';
import { Injectable } from '@angular/core';
import {Observable, of } from 'rxjs';
import {MoyaLocale} from './moya-locale.model';
import {HttpClient} from '@angular/common/http';
import {TranslateService} from '@ngx-translate/core';
import {MOYA_REST_URL} from '../../shared/config/moya.config';
export const ENGLISH = 'en';
export const FINNISH = 'fi';
export const SWEDISH = 'sv';
export const DEFAULT_LOCALE = FINNISH;
const LOCALSTORAGE_NAME = 'currently used locale code';
@Injectable()
export class LocaleService {
selectedLocale: string;
constructor(private http: HttpClient, private translate: TranslateService) {
this.translate.setDefaultLang(ENGLISH);
this.getUserLocale().subscribe();
}
/**
* Returns same locale you did give this as a parameter.
*
* @param {string} locale
* @param {boolean} save
* @return {string}
*/
selectLocale(locale: string, save = false): string {
if (![ENGLISH, FINNISH, SWEDISH].includes(locale)) {
return;
}
this.translate.use(locale);
this.selectedLocale = locale;
if (save) {
this.setUserLocale(locale);
}
return locale;
}
/**
* Order of Locale:
* 1. User's locale from database
* 2. User's locale from cookie
* 3. Event's locale from database
* 4. Default
*
* @return {Observable<string>} Return current locale as a string. No errors.
*/
public getUserLocale(): Observable<string> {
// If there is already locale, don't bother of running this rest stuff again
if (this.selectedLocale) {
return new Observable<string>(x => x.next(this.selectedLocale));
}
return this.http.get<MoyaLocale>(MOYA_REST_URL + '/v3/locale/').pipe(
catchError(x =>
of({} as MoyaLocale)
),
map(locale => {
if (locale && locale.userLocale) {
return this.selectLocale(locale.userLocale);
}
const storageLocale = localStorage.getItem(LOCALSTORAGE_NAME);
if (storageLocale) {
return this.selectLocale(storageLocale);
}
if (locale.eventLocale) {
return this.selectLocale(locale.eventLocale);
}
return this.selectLocale(DEFAULT_LOCALE);
}), );
}
/**
* Store user's locale. This will store it to server. Or server is not available, into localstorage.
*
* There is no errors
* @param {string} locale
*/
public setUserLocale(locale: string): void {
const newLocale: MoyaLocale = {
userLocale: locale,
eventLocale: undefined
};
// let's save locale to database, if it fails, we save it into localstorage. No errors to show for user.
this.http.post(MOYA_REST_URL + '/v3/locale/', newLocale).pipe(catchError(x => {
localStorage.setItem(LOCALSTORAGE_NAME, locale);
return 'ok';
})).subscribe();
}
}