1
- const storage = { }
1
+ /**
2
+ * @typedef {import('../types/cache').TCacheMethods } TCacheMethods
3
+ */
2
4
3
5
/**
4
6
* Key-value based cache with expire feature.
7
+ * @returns {TCacheMethods }
5
8
*/
6
9
const Cache = ( ) => {
10
+ const storage = { }
11
+
7
12
/**
8
13
* Checks if the key is close to expire.
9
14
* @private
10
15
*/
11
- const timer = setInterval ( ( ) => {
16
+ setInterval ( ( ) => {
12
17
const now = Date . now ( )
13
18
for ( const key in storage ) {
14
19
const { date, expire } = storage [ key ]
@@ -24,28 +29,23 @@ const Cache = () => {
24
29
* @param {String } key The key for storing data.
25
30
* @returns {any }
26
31
*/
27
- const getFromCache = ( key ) => storage [ key ] ? storage [ key ] . value : undefined
32
+ const getValueBy = ( key ) => storage [ key ] ? storage [ key ] . value : undefined
28
33
29
34
/**
30
35
* Stores data with given `key`, `expire` and `value`
31
36
* @param {String } key The key for storing data.
32
37
* @param {Number } [expire] The seconds to expire.
33
38
* @returns {(any) => any }
34
39
*/
35
- const storeInCache = ( key , expire = Infinity ) => ( value ) => {
40
+ const store = ( key , expire = Infinity ) => ( value ) => {
36
41
storage [ key ] = { }
37
42
storage [ key ] . value = value
38
43
storage [ key ] . date = Date . now ( )
39
44
storage [ key ] . expire = expire
40
45
41
- return getFromCache ( key )
46
+ return getValueBy ( key )
42
47
}
43
48
44
- /**
45
- * Stops searching for values to expire.
46
- */
47
- const stopCache = ( ) => clearInterval ( timer )
48
-
49
49
/**
50
50
* Get stored keys.
51
51
* @returns {String[] }
@@ -54,15 +54,14 @@ const Cache = () => {
54
54
55
55
/**
56
56
* Gets all key value pairs from cache.
57
- * @returns {Array } Array of key value pairs.
57
+ * @returns {any[] } Array of key value pairs.
58
58
*/
59
- const getKeyValuePairs = ( ) => getKeys ( ) . map ( ( key ) => storage [ key ] . value )
59
+ const getKeyValuePairs = ( ) => getKeys ( ) . map ( ( key ) => ( { key , value : storage [ key ] . value } ) )
60
60
61
61
return {
62
- getFromCache,
63
- getFromCacheAsync : ( key ) => Promise . resolve ( getFromCache ( key ) ) ,
64
- storeInCache,
65
- stopCache,
62
+ getValueBy,
63
+ getValueByAsync : ( key ) => Promise . resolve ( getValueBy ( key ) ) ,
64
+ store,
66
65
getKeys,
67
66
getKeyValuePairs
68
67
}
0 commit comments