Initial commit
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { getPool } from '$lib/server/db';
|
||||
|
||||
export async function GET() {
|
||||
const pool = getPool();
|
||||
let database: 'disabled' | 'up' | 'down' = 'disabled';
|
||||
|
||||
if (pool) {
|
||||
try {
|
||||
await pool.query('select 1');
|
||||
database = 'up';
|
||||
} catch (error) {
|
||||
console.error('Health check database query failed.', error);
|
||||
database = 'down';
|
||||
}
|
||||
}
|
||||
|
||||
return json(
|
||||
{
|
||||
status: database === 'down' ? 'degraded' : 'ok',
|
||||
database,
|
||||
timestamp: new Date().toISOString()
|
||||
},
|
||||
{
|
||||
status: database === 'down' ? 503 : 200
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('$lib/server/db', () => ({
|
||||
getPool: vi.fn()
|
||||
}));
|
||||
|
||||
import { getPool } from '$lib/server/db';
|
||||
import { GET } from './+server';
|
||||
|
||||
describe('health endpoint', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(getPool).mockReset();
|
||||
});
|
||||
|
||||
it('reports a disabled database when no connection string is configured', async () => {
|
||||
vi.mocked(getPool).mockReturnValue(null);
|
||||
|
||||
const response = await GET();
|
||||
const body = await response.json();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(body).toMatchObject({
|
||||
status: 'ok',
|
||||
database: 'disabled'
|
||||
});
|
||||
});
|
||||
|
||||
it('reports an available database when the query succeeds', async () => {
|
||||
vi.mocked(getPool).mockReturnValue({
|
||||
query: vi.fn().mockResolvedValue({})
|
||||
} as never);
|
||||
|
||||
const response = await GET();
|
||||
const body = await response.json();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(body).toMatchObject({
|
||||
status: 'ok',
|
||||
database: 'up'
|
||||
});
|
||||
});
|
||||
|
||||
it('reports a degraded status when the database query fails', async () => {
|
||||
vi.mocked(getPool).mockReturnValue({
|
||||
query: vi.fn().mockRejectedValue(new Error('connection refused'))
|
||||
} as never);
|
||||
|
||||
const response = await GET();
|
||||
const body = await response.json();
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
expect(body).toMatchObject({
|
||||
status: 'degraded',
|
||||
database: 'down'
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user