diff --git a/src/server.test.ts b/src/server.test.ts index 8aae978..ae1fe45 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -52,6 +52,19 @@ describe("API endpoints", () => { }); }); + it("POST /echo accepts a 500-character message", async () => { + const message = "a".repeat(500); + + const response = await app.inject({ + method: "POST", + url: "/echo", + payload: { message }, + }); + + assert.equal(response.statusCode, 200); + assert.deepEqual(response.json(), { message }); + }); + it("POST /echo rejects an empty message", async () => { const response = await app.inject({ method: "POST", @@ -67,6 +80,21 @@ describe("API endpoints", () => { }); }); + it("POST /echo rejects a message longer than 500 characters", async () => { + const message = "a".repeat(501); + + 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 3b5118a..2587f6f 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,6 +1,10 @@ import Fastify from "fastify"; import { z } from "zod"; +const echoSchema = z.object({ + message: z.string().min(1).max(500), +}); + export const buildApp = () => { const app = Fastify({ logger: true, @@ -18,11 +22,7 @@ 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); + const result = echoSchema.safeParse(request.body); if (!result.success) { return reply.code(400).send({