-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathBatch.service.ts
More file actions
112 lines (94 loc) · 3.27 KB
/
Batch.service.ts
File metadata and controls
112 lines (94 loc) · 3.27 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
import {BATCH_KEY, Events} from "../constants";
import { App } from "../app";
import { BatchStorage } from "../repositories/BatchStorage";
export class BatchService {
private appModule: App;
private storage: BatchStorage;
private backoff: number = 1;
private intervalId: number | null = null;
private batchInterval: number = 2000;
private readonly BATCH_KEY: string = BATCH_KEY;
constructor(appModule: App) {
this.appModule = appModule;
this.storage = new BatchStorage(this.BATCH_KEY + '-' + this.appModule.getApiToken() + '-' + this.appModule.getAppName());
}
public init() {
if (document.readyState === 'complete') {
this.startBatchingWithInterval();
} else {
document.onreadystatechange = () => {
if (document.readyState == "complete") {
this.startBatchingWithInterval();
}
}
}
}
private startBatchingWithInterval() {
this.appModule.collectEvent(Events.INIT);
this.startBatching();
}
public stopBatching() {
if (this.intervalId !== null) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
public collect(event_name: string, requestBody?: Record<string, any>) {
if (document.readyState === 'complete') {
this.storage.addToStorage(event_name, requestBody);
} else {
const onLoad = () => {
this.storage.addToStorage(event_name, requestBody);
}
setTimeout(() => {
if (document.readyState === 'complete') {
onLoad();
} else {
window.addEventListener('load', onLoad)
}
}, 0);
}
}
public startBatching() {
if (this.intervalId === null) {
this.intervalId = window.setInterval(() => this.processQueue(), this.batchInterval);
}
}
private processQueue() {
const data: Record<string, any>[] = this.storage.getBatch();
if ((data.length !== 0) && (window.navigator.onLine)) {
this.sendBatch(data.slice(0,20));
}
}
private sendBatch(batch: Record<string, any>[]) {
this.stopBatching();
this.appModule.recordEvents(batch).then((res: Response)=> {
if (String(res.status) === '429') {
this.startBatching();
return;
}
if (String(res.status)[0] === '4') {
return;
}
if (String(res.status)[0] === '5') {
if (this.backoff < 5){
this.backoff++;
this.batchInterval = this.batchInterval * 2.71;
this.startBatching();
}
return;
}
this.backoff = 1;
this.batchInterval = 2000;
this.storage.setItem(this.storage.getBatch()
.filter(cachedEvent =>
!batch.some(event =>
JSON.stringify(cachedEvent) === JSON.stringify(event)))
);
this.startBatching();
}, (error) => {
console.log(error);
this.startBatching();
});
}
}