@@ -12,7 +12,7 @@ const cachePool = (opt = { maximumSize: CACHE_SIZE_MB }) => {
12
12
let hits = 0 ;
13
13
14
14
/**
15
- * Get an API Respnose from cacheStore.
15
+ * Get an API Response from cacheStore.
16
16
* @param {string } key
17
17
* @returns {null | object }
18
18
*/
@@ -32,7 +32,12 @@ const cachePool = (opt = { maximumSize: CACHE_SIZE_MB }) => {
32
32
}
33
33
34
34
hits += 1 ;
35
- return JSON . parse ( cachedData . response ) ;
35
+ try {
36
+ return JSON . parse ( cachedData . response ) ;
37
+ } catch ( err ) {
38
+ logger . error ( `Error while parsing cachedData.response ${ err } ` ) ;
39
+ throw err ;
40
+ }
36
41
} ;
37
42
38
43
/**
@@ -69,43 +74,35 @@ const pool = cachePool();
69
74
*/
70
75
const cache = ( data = { priority : 2 , expiry : CACHE_EXPIRY_TIME_MIN } ) => {
71
76
return async ( req , res , next ) => {
72
- const key = "__cache__" + req . method + req . originalUrl ;
73
- const cacheData = pool . get ( key ) ;
74
-
75
- if ( cacheData ) {
76
- res . send ( cacheData ) ;
77
- } else {
78
- /**
79
- * As we do not have data in our cache we call the next middleware,
80
- * intercept the response being sent from middleware and store it in cache.
81
- * */
82
- const chunks = [ ] ;
83
- const oldWrite = res . write ;
84
- const oldEnd = res . end ;
85
-
86
- res . write = ( chunk , ...args ) => {
87
- chunks . push ( chunk ) ;
88
- return oldWrite . apply ( res , [ chunk , ...args ] ) ;
89
- } ;
90
-
91
- res . end = ( chunk , ...args ) => {
92
- if ( chunk ) {
93
- chunks . push ( chunk ) ;
94
- }
95
-
96
- const apiResponse = Buffer . concat ( chunks ) . toString ( ) ;
97
-
98
- const cacheValue = {
99
- priority : data . priority ,
100
- response : apiResponse ,
101
- expiry : new Date ( ) . getTime ( ) + minutesToMilliseconds ( data . expiry ) ,
102
- size : Buffer . byteLength ( apiResponse ) ,
77
+ try {
78
+ const key = "__cache__" + req . method + req . originalUrl ;
79
+ const cacheData = pool . get ( key ) ;
80
+
81
+ if ( cacheData ) {
82
+ res . send ( cacheData ) ;
83
+ } else {
84
+ /**
85
+ * As we do not have data in our cache we call the next middleware,
86
+ * intercept the response being sent from middleware and store it in cache.
87
+ * */
88
+ const oldSend = res . send ;
89
+
90
+ res . send = ( body ) => {
91
+ const cacheValue = {
92
+ priority : data . priority ,
93
+ response : body ,
94
+ expiry : new Date ( ) . getTime ( ) + minutesToMilliseconds ( data . expiry ) ,
95
+ size : Buffer . byteLength ( body ) ,
96
+ } ;
97
+ pool . set ( key , cacheValue ) ;
98
+ res . send = oldSend ;
99
+ return res . send ( body ) ;
103
100
} ;
104
101
105
- pool . set ( key , cacheValue ) ;
106
- return oldEnd . apply ( res , [ chunk , ... args ] ) ;
107
- } ;
108
-
102
+ next ( ) ;
103
+ }
104
+ } catch ( err ) {
105
+ logger . error ( `Error while getting cached tasks response ${ err } ` ) ;
109
106
next ( ) ;
110
107
}
111
108
} ;
0 commit comments