Skip to content

Commit 970eaed

Browse files
committed
fix cachiung
1 parent 0e18316 commit 970eaed

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

cache/cache.test.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,31 @@ describe('Cache Middleware Tests', () => {
122122
cacheQuery(mockReq, mockRes, mockNext)
123123
expect(mockRes.headers['X-Cache']).toBe('MISS')
124124
})
125+
126+
it('should create different cache keys for different query bodies', () => {
127+
mockReq.method = 'POST'
128+
mockReq.query = { limit: '100', skip: '0' }
129+
130+
// First request for Annotations
131+
mockReq.body = { type: 'Annotation' }
132+
cacheQuery(mockReq, mockRes, mockNext)
133+
mockRes.json([{ id: '1', type: 'Annotation' }])
134+
135+
// Reset mocks for second request
136+
mockRes.headers = {}
137+
const jsonSpy = jest.fn()
138+
mockRes.json = jsonSpy
139+
mockNext = jest.fn()
140+
141+
// Second request for Person (different body, should be MISS)
142+
mockReq.body = { type: 'Person' }
143+
cacheQuery(mockReq, mockRes, mockNext)
144+
145+
expect(mockRes.headers['X-Cache']).toBe('MISS')
146+
expect(mockNext).toHaveBeenCalled()
147+
// json was replaced by middleware, so check it wasn't called before next()
148+
expect(jsonSpy).not.toHaveBeenCalled()
149+
})
125150
})
126151

127152
describe('cacheSearch middleware', () => {

cache/index.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,18 @@ class LRUCache {
5656
return `id:${params}`
5757
}
5858
// For query and search, create a stable key from the params object
59-
const sortedParams = JSON.stringify(params, Object.keys(params).sort())
59+
// Use a custom replacer to ensure consistent key ordering at all levels
60+
const sortedParams = JSON.stringify(params, (key, value) => {
61+
if (value && typeof value === 'object' && !Array.isArray(value)) {
62+
return Object.keys(value)
63+
.sort()
64+
.reduce((sorted, key) => {
65+
sorted[key] = value[key]
66+
return sorted
67+
}, {})
68+
}
69+
return value
70+
})
6071
return `${type}:${sortedParams}`
6172
}
6273

0 commit comments

Comments
 (0)