Lets add zod to add solid input validation and return erroneous status codes if the input is incorrect
npm install zod
index.tsimport express from "express";
import { z } from 'zod'
export const app = express();
app.use(express.json());
const zodSchemaForSum = z.object({
a: z.number(),
b: z.number()
})
app.post("/sum", (req, res) => {
const parsedData = zodSchemaForSum.safeParse(req.body)
if (!parsedData.success) {
return res.status(411).json({
message: "Incorrect inputs"
})
}
const answer = parsedData.data.a + parsedData.data.b
res.json({
answer
})
});
app.get("/sum", (req, res) => {
const parsedResponse = zodSchemaForSum.safeParse({
a: Number(req.headers["a"]),
b: Number(req.headers["b"])
})
if (!parsedResponse.success) {
return res.status(411).json({
message: "Incorrect inputs"
})
}
const answer = parsedResponse.data.a + parsedResponse.data.b;
res.json({
answer
})
});
sum.test.tsimport { describe, expect, test, it } from '@jest/globals';
import request from "supertest";
import { app } from "../src/index.js"
describe("POST /sum", () => {
it("should return the sum of two numbers", async () => {
const res = await request(app).post("/sum").send({
a: 1,
b: 2
});
expect(res.statusCode).toBe(200);
expect(res.body.answer).toBe(3);
});
it("should return 411 if no inputs are provided", async () => {
const res = await request(app).post("/sum").send({});
expect(res.statusCode).toBe(411);
expect(res.body.message).toBe("Incorrect inputs");
});
});
describe("GET /sum", () => {
it("should return the sum of two numbers", async () => {
const res = await request(app)
.get("/sum")
.set({
a: "1",
b: "2"
})
.send();
expect(res.statusCode).toBe(200);
expect(res.body.answer).toBe(3);
});
it("should return 411 if no inputs are provided", async () => {
const res = await request(app)
.get("/sum").send();
expect(res.statusCode).toBe(411);
});
});