@@ -54,8 +54,31 @@ export default function addTTL<
54
54
} = addEmitter < TTLCache < V , K > , V , K > ( < TTLCache < V , K > > < unknown > cache ) ;
55
55
56
56
const
57
- cacheWithTTL : TTLCache < V , K > = Object . create ( cache ) ,
58
- ttlTimers = new Map < K , number | NodeJS . Timeout > ( ) ;
57
+ ttlStore = new Map < K , number > ( ) ,
58
+ dateStore = new Map < K , number > ( ) ;
59
+
60
+ const
61
+ cacheWithTTL : TTLCache < V , K > = Object . create ( cache ) ;
62
+
63
+ cacheWithTTL . get = ( key : K ) => {
64
+ const
65
+ dateSet = dateStore . get ( key ) ,
66
+ ttl = ttlStore . get ( key ) ;
67
+
68
+ if ( dateSet != null && ttl != null ) {
69
+ const
70
+ expired = Date . now ( ) - dateSet > ttl ;
71
+
72
+ if ( expired ) {
73
+ cacheWithTTL . remove ( key ) ;
74
+ return ;
75
+ }
76
+ }
77
+
78
+ return cache . get ( key ) ;
79
+ } ;
80
+
81
+ cacheWithTTL . has = ( key : K ) => cacheWithTTL . get ( key ) !== undefined ;
59
82
60
83
cacheWithTTL . set = ( key : K , value : V , opts ?: TTLDecoratorOptions & Parameters < T [ 'set' ] > [ 2 ] ) => {
61
84
updateTTL ( key , opts ?. ttl ) ;
@@ -68,9 +91,10 @@ export default function addTTL<
68
91
} ;
69
92
70
93
cacheWithTTL . removeTTLFrom = ( key : K ) => {
71
- if ( ttlTimers . has ( key ) ) {
72
- clearTimeout ( < number > ttlTimers . get ( key ) ) ;
73
- ttlTimers . delete ( key ) ;
94
+ if ( ttlStore . has ( key ) || dateStore . has ( key ) ) {
95
+ ttlStore . delete ( key ) ;
96
+ dateStore . delete ( key ) ;
97
+
74
98
return true ;
75
99
}
76
100
@@ -81,9 +105,13 @@ export default function addTTL<
81
105
const
82
106
removed = originalClear ( filter ) ;
83
107
84
- removed . forEach ( ( _ , key ) => {
85
- cacheWithTTL . removeTTLFrom ( key ) ;
86
- } ) ;
108
+ if ( filter == null ) {
109
+ ttlStore . clear ( ) ;
110
+ dateStore . clear ( ) ;
111
+
112
+ } else {
113
+ removed . forEach ( ( _ , key ) => cacheWithTTL . removeTTLFrom ( key ) ) ;
114
+ }
87
115
88
116
return removed ;
89
117
} ;
@@ -101,9 +129,11 @@ export default function addTTL<
101
129
return cacheWithTTL ;
102
130
103
131
function updateTTL ( key : K , optionTTL ?: number ) : void {
104
- if ( optionTTL != null || ttl != null ) {
105
- const time = optionTTL ?? ttl ;
106
- ttlTimers . set ( key , setTimeout ( ( ) => cacheWithTTL . remove ( key ) , time ) ) ;
132
+ const time = optionTTL ?? ttl ;
133
+
134
+ if ( time != null ) {
135
+ ttlStore . set ( key , time ) ;
136
+ dateStore . set ( key , Date . now ( ) ) ;
107
137
108
138
} else {
109
139
cacheWithTTL . removeTTLFrom ( key ) ;
0 commit comments