1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | export class Cacher {
|
9 |
|
10 | constructor(option) {
|
11 | this.cacheMap = new Map()
|
12 | this.option = option
|
13 | this.maxCacheSize = option.maxCacheSize
|
14 | this.ttl = option.ttl
|
15 | this.filters = []
|
16 | }
|
17 |
|
18 | addFilter(reg) {
|
19 | this.filters.push(reg)
|
20 | }
|
21 |
|
22 | removeFilter(reg) {
|
23 | let index = this.filters.indexOf(reg)
|
24 | if(index !== -1) {
|
25 | this.filters.splice(index, 1)
|
26 | }
|
27 | }
|
28 |
|
29 | setCache(key, value) {
|
30 | this.cacheMap.set(JSON.stringify(key), value)
|
31 | if(this.maxCacheSize && this.cacheMap.size > this.maxCacheSize) {
|
32 | this.cacheMap.delete([...(this.cacheMap).keys()][0])
|
33 | }
|
34 | if(this.ttl) {
|
35 | setTimeout(() => {
|
36 | this.cacheMap.delete(key)
|
37 | }, this.ttl)
|
38 | }
|
39 | }
|
40 |
|
41 | needCache(key) {
|
42 | return this.filters.some(reg => {
|
43 | return reg.test(key.url)
|
44 | })
|
45 | }
|
46 |
|
47 | hasCache(key) {
|
48 | return this.cacheMap.has(JSON.stringify(key))
|
49 | }
|
50 |
|
51 | getCache(key) {
|
52 | return this.cacheMap.get(JSON.stringify(key))
|
53 | }
|
54 |
|
55 | }
|