From 554686744901376f005d139f983d783668e402ff Mon Sep 17 00:00:00 2001 From: Brandon Wolfgang Date: Wed, 21 Oct 2026 19:30:31 -0500 Subject: [PATCH] =?UTF-8?q?test:=20add=20validation=20tests=20for=20POST?= =?UTF-8?q?=20/echo=20-=20Test=20successful=20echo=20responses=20for=20val?= =?UTF-8?q?id=20messages=20-=20Verify=20empty=20messages=20are=20rejected?= =?UTF-8?q?=20with=20HTTP=20400=20-=20Validate=20request=20bodies=20using?= =?UTF-8?q?=20a=20Zod=20schema=20with=20a=201=E2=80=93500=20character=20li?= =?UTF-8?q?mit=20-=20Return=20a=20consistent=20error=20response=20for=20in?= =?UTF-8?q?valid=20request=20bodies?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/server.test.ts | 30 ++++++++++++++++++++++++++++++ src/server.ts | 19 +++++++++++++++++++ 2 files changed, 49 insertions(+) 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; };