-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathImpressionCountsCacheInMemory.ts
More file actions
71 lines (61 loc) · 1.85 KB
/
Copy pathImpressionCountsCacheInMemory.ts
File metadata and controls
71 lines (61 loc) · 1.85 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
import { truncateTimeFrame } from '../../utils/time';
import { DEFAULT_CACHE_SIZE } from '../inRedis/constants';
import { IImpressionCountsCacheSync } from '../types';
export class ImpressionCountsCacheInMemory implements IImpressionCountsCacheSync {
public name = 'impression counts';
protected cache: Record<string, number> = {};
private readonly maxStorage: number;
protected onFullQueue?: () => void;
private cacheSize = 0;
constructor(impressionCountsCacheSize = DEFAULT_CACHE_SIZE) {
this.maxStorage = impressionCountsCacheSize;
}
/**
* Builds key to be stored in the cache with the featureName and the timeFrame truncated.
*/
private _makeKey(featureName: string, timeFrame: number) {
return `${featureName}::${truncateTimeFrame(timeFrame)}`;
}
/**
* Increments the quantity of impressions with the passed featureName and timeFrame.
*/
track(featureName: string, timeFrame: number, amount: number) {
const key = this._makeKey(featureName, timeFrame);
const currentAmount = this.cache[key];
this.cache[key] = currentAmount ? currentAmount + amount : amount;
if (this.onFullQueue) {
this.cacheSize = this.cacheSize + amount;
if (this.cacheSize >= this.maxStorage) {
this.onFullQueue();
}
}
}
/**
* Pop the collected data, used as payload for posting.
*/
pop(toMerge?: Record<string, number>) {
const data = this.cache;
this.clear();
if (toMerge) {
Object.keys(data).forEach((key) => {
if (toMerge[key]) toMerge[key] += data[key];
else toMerge[key] = data[key];
});
return toMerge;
}
return data;
}
/**
* Clear the data stored on the cache.
*/
clear() {
this.cache = {};
this.cacheSize = 0;
}
/**
* Check if the cache is empty.
*/
isEmpty() {
return Object.keys(this.cache).length === 0;
}
}