Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/cache/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,34 @@ describe('Cache Module', () => {
expect(result).toEqual([{ id: 1, name: 'John' }])
})

it('should return null if cached result JSON is malformed', async () => {
const consoleSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {})
const cachedData = {
timestamp: new Date().toISOString(),
ttl: 300,
results: '{"id":',
}

vi.mocked(mockDataSource.rpc.executeQuery).mockResolvedValue([
cachedData,
])

const result = await beforeQueryCache({
sql: 'SELECT * FROM users',
params: [],
dataSource: mockDataSource,
})

expect(result).toBeNull()
expect(consoleSpy).toHaveBeenCalledWith(
'Error parsing cached query results:',
expect.any(SyntaxError)
)
consoleSpy.mockRestore()
})

it('should return null if cache is expired', async () => {
const expiredCache = {
timestamp: new Date(Date.now() - 1000 * 3600).toISOString(), // 1 hour old
Expand Down
7 changes: 6 additions & 1 deletion src/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,12 @@ export async function beforeQueryCache(opts: {
const expirationTime = new Date(timestamp).getTime() + ttl * 1000

if (Date.now() < expirationTime) {
return JSON.parse(results)
try {
return JSON.parse(results)
} catch (error) {
console.error('Error parsing cached query results:', error)
return null
}
}
}

Expand Down