diff --git a/src/server.test.ts b/src/server.test.ts index cd48ff4..8aae978 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -37,6 +37,36 @@ describe("API endpoints", () => { }); }); + it("POST /echo returns the validated message", async () => { + const response = await app.inject({ + method: "POST", + url: "/echo", + payload: { + message: "Hello, world!", + }, + }); + + assert.equal(response.statusCode, 200); + assert.deepEqual(response.json(), { + message: "Hello, world!", + }); + }); + + it("POST /echo rejects an empty message", async () => { + const response = await app.inject({ + method: "POST", + url: "/echo", + payload: { + message: "", + }, + }); + + assert.equal(response.statusCode, 400); + assert.deepEqual(response.json(), { + error: "Invalid request body", + }); + }); + it("returns 404 for an unknown endpoint", async () => { const response = await app.inject({ method: "GET", diff --git a/src/server.ts b/src/server.ts index 4730318..3b5118a 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,4 +1,5 @@ import Fastify from "fastify"; +import { z } from "zod"; export const buildApp = () => { const app = Fastify({ @@ -16,6 +17,24 @@ export const buildApp = () => { }, })); + app.post("/echo", async (request, reply) => { + const schema = z.object({ + message: z.string().min(1).max(500), + }); + + const result = schema.safeParse(request.body); + + if (!result.success) { + return reply.code(400).send({ + error: "Invalid request body", + }); + } + + return { + message: result.data.message, + }; + }); + return app; };