From d44f2412de11b5006c355ea54d16e3f8b9515717 Mon Sep 17 00:00:00 2001 From: attaboy11 Date: Sat, 30 May 2026 23:35:13 +0100 Subject: [PATCH] test: cover malformed query cache fallback --- src/cache/index.test.ts | 28 ++++++++++++++++++++++++++++ src/cache/index.ts | 7 ++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/cache/index.test.ts b/src/cache/index.test.ts index 8438ab0..310795e 100644 --- a/src/cache/index.test.ts +++ b/src/cache/index.test.ts @@ -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 diff --git a/src/cache/index.ts b/src/cache/index.ts index d98d750..3639f7b 100644 --- a/src/cache/index.ts +++ b/src/cache/index.ts @@ -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 + } } }