@@ -18,7 +18,9 @@ async function getBucketFromClient(
1818 redisClient : RedisClientType ,
1919 uuid : string
2020) : Promise < RedisBucket > {
21- return redisClient . get ( uuid ) . then ( ( res ) => JSON . parse ( res || '{}' ) ) ;
21+ const res = await redisClient . get ( uuid ) ;
22+ if ( res === undefined || res === null ) return { tokens : - 1 , timestamp : - 1 } ;
23+ return JSON . parse ( res ! ) ;
2224}
2325
2426async function setTokenCountInClient (
@@ -31,7 +33,7 @@ async function setTokenCountInClient(
3133 await redisClient . set ( uuid , JSON . stringify ( value ) ) ;
3234}
3335
34- xdescribe ( 'Test TokenBucket Rate Limiter' , ( ) => {
36+ describe ( 'Test TokenBucket Rate Limiter' , ( ) => {
3537 beforeEach ( async ( ) => {
3638 // Initialize a new token bucket before each test
3739 // create a mock user
@@ -50,7 +52,7 @@ xdescribe('Test TokenBucket Rate Limiter', () => {
5052 CAPACITY - withdraw5
5153 ) ;
5254 const tokenCountFull = await getBucketFromClient ( client , user1 ) ;
53- expect ( tokenCountFull ) . toBe ( CAPACITY - withdraw5 ) ;
55+ expect ( tokenCountFull . tokens ) . toBe ( CAPACITY - withdraw5 ) ;
5456 } ) ;
5557
5658 test ( 'bucket is partially full and request has leftover tokens' , async ( ) => {
@@ -69,7 +71,7 @@ xdescribe('Test TokenBucket Rate Limiter', () => {
6971 ) . tokens
7072 ) . toBe ( CAPACITY - ( initial + partialWithdraw ) ) ;
7173 const tokenCountPartial = await getBucketFromClient ( client , user2 ) ;
72- expect ( tokenCountPartial ) . toBe ( CAPACITY - ( initial + partialWithdraw ) ) ;
74+ expect ( tokenCountPartial . tokens ) . toBe ( CAPACITY - ( initial + partialWithdraw ) ) ;
7375 } ) ;
7476
7577 // Bucket partially full and no leftover tokens after reqeust
@@ -78,15 +80,15 @@ xdescribe('Test TokenBucket Rate Limiter', () => {
7880 await setTokenCountInClient ( client , user2 , initial , timestamp ) ;
7981 expect ( ( await limiter . processRequest ( user2 , timestamp , initial ) ) . tokens ) . toBe ( 0 ) ;
8082 const tokenCountPartialToEmpty = await getBucketFromClient ( client , user2 ) ;
81- expect ( tokenCountPartialToEmpty ) . toBe ( 0 ) ;
83+ expect ( tokenCountPartialToEmpty . tokens ) . toBe ( 0 ) ;
8284 } ) ;
8385
8486 // Bucket initially empty but enough time elapsed to paritally fill bucket since last request
8587 test ( 'bucket is initially empty but enough time has elapsed to partially fill the bucket' , async ( ) => {
8688 await setTokenCountInClient ( client , user4 , 0 , timestamp ) ;
8789 expect ( ( await limiter . processRequest ( user4 , timestamp + 6000 , 4 ) ) . tokens ) . toBe ( 2 ) ;
8890 const count = await getBucketFromClient ( client , user4 ) ;
89- expect ( count ) . toBe ( 2 ) ;
91+ expect ( count . tokens ) . toBe ( 2 ) ;
9092 } ) ;
9193 } ) ;
9294
0 commit comments