@@ -5,44 +5,85 @@ Simple caching solution in Typescript.
5
5
6
6
## ` Cache<ValueType> `
7
7
8
+ ### Load or Generate
9
+
8
10
``` ts
9
11
const cache = new Cache <string >();
10
12
11
- const cacheKey = ' abc123' ;
13
+ // Load from cache.
14
+ // If not found, value will be generated and stored in cache.
15
+ cache .load (' key_1' , () => {
16
+ // Some expensive operation
17
+ return ' Lorem ipsum' ;
18
+ }); // Return type is string
12
19
13
- /**
14
- * Load from cache.
15
- * If not found, value will be generated and stored in cache.
16
- */
17
- cache .load (cacheKey , () => {
18
- const result = ' Lorem ipsum' ;
20
+ cache .has (' key_1' ); // true
21
+ cache .load (' key_1' ); // 'Lorem ipsum'
19
22
20
- // Some expensive operation
21
- // ...
22
23
23
- return result
24
- }); // -> string
24
+ // Load from cache without generating.
25
+ cache .load (' key_2' ); // Return type is string | undefined
26
+
27
+ // Save to cache.
28
+ cache .save (' key_2' , ' Lorem ipsum' );
29
+
30
+ // Check if cache exists.
31
+ cache .has (' key_2' ); // true
32
+ cache .load (' key_2' ); // 'Lorem ipsum'
33
+ ```
34
+
35
+
36
+ ### Invalidation
37
+ #### Expiration
38
+ ``` ts
39
+ const cache = new Cache <number >();
25
40
41
+ cache .save (' key' , 42 , {
42
+ expire: 1000 // Expire after 1 second.
43
+ });
26
44
27
- /**
28
- * Load from cache.
29
- */
30
- cache .load (cacheKey ); // -> string | undefined
31
45
46
+ // Works with load generator too.
47
+ cache .load (' key' , () => 42 , { expire: 1000 });
48
+ ```
32
49
33
- /**
34
- * Save to cache.
35
- */
36
- cache .save (cacheKey , ' Lorem ipsum' );
50
+ ``` ts
51
+ const cache = new Cache <number >();
37
52
53
+ cache .save (' key' , 42 , {
54
+ expire: 1000 ,
55
+ sliding: true // Update expiration after each load
56
+ });
57
+ ```
38
58
39
- /**
40
- * Check if cache exists.
41
- */
42
- cache .has (cacheKey ); // -> boolean
59
+ #### Files
60
+ ``` ts
61
+ const cache = new Cache <string >();
43
62
63
+ cache .save (' key' , " My text data" , {
64
+ files: [
65
+ ' file_1.txt' ,
66
+ ' file_2.txt'
67
+ ] // Expired when some file is modified or deleted.
68
+ });
44
69
```
45
70
71
+ #### Callbacks
72
+ ``` ts
73
+ const cache = new Cache <string >();
74
+
75
+ function isValid(): boolean {
76
+ // ...
77
+ return true ;
78
+ }
79
+
80
+ cache .save (' key' , " My text data" , {
81
+ callbacks: [
82
+ isValid ,
83
+ () => false ,
84
+ ] // Expired when some callback return false.
85
+ });
86
+ ```
46
87
47
88
48
89
## Documentation 📖
0 commit comments