/
rcdata.ts
64 lines (59 loc) · 2.28 KB
/
rcdata.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
import {Updater} from './updater';
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions'
export class RemoteConfigData {
remoteConfig: admin.remoteConfig.RemoteConfig;
updaters: Record<string, Updater>;
constructor(app: admin.app.App) {
this.remoteConfig = admin.remoteConfig(app);
this.updaters = {};
this.listenToRCChanges();
}
async getSearchTermsForLanguage(language: string) {
console.info('Getting template...');
const template = await this.remoteConfig.getTemplate();
console.debug('Checking condition');
let condition: string;
switch (language) {
case 'es':
condition = 'Spanish users';
break;
default:
condition = 'Default language users';
break;
}
console.debug('Parsing JSON');
return JSON.parse(template.parameters['search_terms'].conditionalValues[condition]['value']);
}
subscribeUpdaters(updaters: Record<string, Updater>) {
this.updaters = updaters;
}
listenToRCChanges() {
console.info('Listening to changes in RemoteConfig...');
functions.remoteConfig.onUpdate((version, _) => {
console.debug(`RemoteConfig values have changed - version: ${version}`);
return admin.credential.applicationDefault().getAccessToken()
// tslint:disable-next-line:no-shadowed-variable
.then(_ => {
this.remoteConfig.getTemplate()
.then(template => {
const languages = Object.keys(template.parameters['search_terms'].conditionalValues);
for (const language of languages) {
const terms = JSON.parse(
template.parameters['search_terms'].conditionalValues[language]['value']
);
try {
console.debug("Updating updater search terms");
if (this.updaters[language].searchTerms.length !== terms.lenght)
this.updaters[language].searchTerms = terms;
} catch (e) {
console.warn(`Updaters are not set yet - ${e}`);
}
}
})
.catch(err => console.warn(`Error while obtaining the template - ${err}`));
})
.catch(err => console.error(`Error while obtaining data from RC: ${err}`));
});
}
}