-
Notifications
You must be signed in to change notification settings - Fork 0
/
replicationHandler.js
64 lines (56 loc) · 1.86 KB
/
replicationHandler.js
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 axios from 'axios';
import config from '../config';
import moment from 'moment';
class Replication {
constructor(db, replicationUrl, storageKey, time = 10000) {
this.db = db;
this.replicationUrl = replicationUrl;
this.storageKey = storageKey;
this.tryReplication = this.tryReplication.bind(this);
this.stopReplication = this.stopReplication.bind(this);
this.tryReplication().then(() => {
this.interval = window.setInterval(this.tryReplication, time);
});
}
stopReplication() {
window.clearInterval(this.interval);
window.localStorage.removeItem(this.storageKey);
}
async tryReplication() {
let rawNextChangeDate = localStorage.getItem(this.storageKey);
let nextChangeDate = moment(rawNextChangeDate).format(
'YYYY-MM-DDTHH:mm:SSS'
);
if (
!rawNextChangeDate ||
nextChangeDate < moment(new Date()).format('YYYY-MM-DDTHH:mm:SSS')
) {
try {
let { data } = await axios.get(this.replicationUrl);
await this.db.bulkDocs({ docs: data });
localStorage.setItem(this.storageKey, this.getNextReplicationDate());
} catch (err) {
if (err.response) {
} // else no response received that means the user is offline (or the server is not working)
}
}
}
getNextReplicationDate() {
let replicationHour = config.replication_starting_hour; // at 9am every morning the new data is here we have to refetch it
let date = new Date();
let nextDate = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
replicationHour
);
if (date.getHours() >= replicationHour) {
nextDate.setDate(nextDate.getDate() + 1);
}
return nextDate;
}
}
const replicateFromSQL = (db, replicationUrl, storageKey) => {
return new Replication(db, replicationUrl, storageKey);
};
export default replicateFromSQL;