Skip to content

Commit e51724f

Browse files
feat(api): implement ingest route and log schema for logging functionality
1 parent f2facff commit e51724f

File tree

4 files changed

+64
-0
lines changed

4 files changed

+64
-0
lines changed

api/app.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import Fastify from 'fastify';
22
import { healthRoute } from './routes/health.route.js';
3+
import { ingestRoute } from './routes/ingest.route.js';
34

45
export const buildApp = () => {
56
const app = Fastify({ logger: true });
@@ -8,5 +9,9 @@ export const buildApp = () => {
89
prefix: '/api/health',
910
});
1011

12+
app.register(ingestRoute, {
13+
prefix: '/api/ingest',
14+
});
15+
1116
return app;
1217
};
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import type { FastifyRequest, FastifyReply } from 'fastify';
2+
import { producer } from '../lib/kafka.js';
3+
import { logSchema } from '../schemas/log.schema.js';
4+
import type { LogInput } from '../schemas/log.schema.js';
5+
6+
export const createLog = async (
7+
request: FastifyRequest<{ Body: LogInput }>,
8+
reply: FastifyReply
9+
) => {
10+
11+
// 1. Validate
12+
const result = logSchema.safeParse(request.body);
13+
14+
if (!result.success) {
15+
return reply.status(400).send({
16+
error: 'Validation Failed',
17+
details: result.error.format()
18+
});
19+
}
20+
21+
const logData = result.data;
22+
23+
try {
24+
// 2. Business Logic
25+
await producer.send({
26+
topic: 'app-logs',
27+
messages: [
28+
{
29+
value: JSON.stringify({
30+
...logData,
31+
timestamp: new Date().toISOString(),
32+
}),
33+
},
34+
],
35+
});
36+
37+
return reply.status(202).send({ status: 'queued', id: crypto.randomUUID() });
38+
39+
} catch (error) {
40+
request.log.error(error);
41+
return reply.status(500).send({ error: 'Failed to queue log' });
42+
}
43+
};

api/routes/ingest.route.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import type { FastifyInstance } from 'fastify';
2+
import { createLog } from '../controllers/ingest.controller.js';
3+
4+
export async function ingestRoute(fastify: FastifyInstance) {
5+
fastify.post('/', createLog);
6+
}

api/schemas/log.schema.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import z from 'zod';
2+
3+
export const logSchema = z.object({
4+
service: z.string().min(1, "Service name is required"),
5+
level: z.enum(['INFO', 'WARN', 'ERROR', 'DEBUG']),
6+
message: z.string().min(1, "Log message cannot be empty"),
7+
metadata: z.record(z.string(), z.any()).optional(),
8+
});
9+
10+
export type LogInput = z.infer<typeof logSchema>;

0 commit comments

Comments
 (0)