/
ChangeWatcher.ts
76 lines (65 loc) · 2.04 KB
/
ChangeWatcher.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
import { stringify } from 'query-string';
import { ApiResponse, StApi } from '../Api';
import { getSession, Session } from '../Session';
import { ChangeNotification } from './ChangeNotification';
export default class ChangeWatcher {
private changeWatchTicker;
private tickInterval: number;
private callback: (changeNotifications: ChangeNotification[]) => any;
private lastServerTimestamp: string | null;
constructor(tickInterval: number, callback: (changeNotifications: ChangeNotification[]) => any) {
this.tickInterval = tickInterval;
this.callback = callback;
}
public async start(): Promise<void> {
if (this.changeWatchTicker) {
return;
}
await this.checkChanges();
this.changeWatchTicker = setInterval(() => this.checkChanges(), this.tickInterval);
}
private async checkChanges(): Promise<void> {
const session: Session | null = await getSession();
if (!session) {
return;
}
const changesNotifications: ChangeNotification[] = await this.getChangesFromApi();
if (changesNotifications.length > 0) {
await this.callback(changesNotifications);
}
}
private async getChangesFromApi() {
const changesNotifications: ChangeNotification[] = [];
const queryString = this.lastServerTimestamp ? 'changes?' + stringify({
since: this.lastServerTimestamp
}) : 'changes';
const apiResponse: ApiResponse = await StApi.get(queryString);
if (apiResponse.serverTimestamp) {
this.lastServerTimestamp = apiResponse.serverTimestamp;
}
if (!apiResponse.data.hasOwnProperty('changes')) {
throw new Error('Changes error');
}
if (apiResponse.data.changes.length > 0) {
apiResponse.data.changes.forEach((item) => {
const change: ChangeNotification = {
id: item.id,
type: item.type,
change: item.change,
};
if (item.version) {
change.version = item.version;
}
changesNotifications.push(change);
});
}
return changesNotifications;
}
public kill() {
clearInterval(this.changeWatchTicker);
this.changeWatchTicker = null;
}
public reset() {
this.lastServerTimestamp = null;
}
}