This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
sigaa-page-cache.ts
106 lines (96 loc) · 2.2 KB
/
sigaa-page-cache.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
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
import { isEqual } from 'lodash';
import { HTTPRequestOptions } from './sigaa-http';
import { Page } from './sigaa-page';
/**
* @category Internal
*/
export interface PageCache {
/**
* Get Page from cache
*/
getPage(
httpOptions: HTTPRequestOptions,
body?: string | Buffer
): Page | undefined;
/**
* Cache a page or update if the same request values
* @param page
*/
storePage(page: Page): void;
/**
* Flush states of instance
*/
clearCachePage(): void;
}
/**
* Store page cache.
* @category Internal
*/
export class SigaaPageCache implements PageCache {
/**
* Array of all pages in cache.
*/
private cachePages: Page[] = [];
/**
* Interval id to clear the cache.
*/
private intervalId?: NodeJS.Timeout;
/**
* Cache page timeout, default is 5 min
*/
public timeoutCache = 5 * 60 * 1000; // 5min
/**
* @inheritdoc
*/
clearCachePage(): void {
if (this.intervalId) {
clearInterval(this.intervalId);
}
this.cachePages = [];
}
/**
* @inheritdoc
*/
storePage(page: Page): void {
if (this.intervalId === undefined) {
this.intervalId = setInterval(() => {
this.cachePages = this.cachePages.filter((cachePage) => {
return !(cachePage.modifiedAt < Date.now() - this.timeoutCache);
});
if (this.cachePages.length === 0 && this.intervalId !== undefined) {
clearInterval(this.intervalId);
}
}, this.timeoutCache);
}
const replace = false;
this.cachePages = this.cachePages.map((cachePage) => {
if (
isEqual(page.requestOptions, cachePage.requestOptions) &&
page.body === cachePage.requestBody
) {
return page;
} else {
return cachePage;
}
});
if (!replace) {
this.cachePages.push(page);
}
if (this.cachePages.length > 15) {
this.cachePages.shift();
}
}
/**
* @inheritdoc
*/
getPage(
httpOptions: HTTPRequestOptions,
body?: string | Buffer
): Page | undefined {
return this.cachePages.find(
(cachePage) =>
isEqual(httpOptions, cachePage.requestOptions) &&
(body === undefined || body === cachePage.requestBody)
);
}
}