There are two approaches to take when you add external services to your backend.
You can
npm i prisma
npx prisma init
schema.prismagenerator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Sum{
id String @id @default(uuid())
a Int
b Int
result Int
}
npx prisma generate
db/index.ts which exports the prisma client. This is needed because we will be mocking this file out eventuallyimport {PrismaClient} from "@prisma/client"
export const prismaClient = new PrismaClient()
//when someone runs the test cases he should get this
// const prismaClient ={
// sum:{
// create:()=>{}
// }
// }
src/index.ts to store the requests in the dbimport express from "express";
import { z } from 'zod'
import {prismaClient} from "../db/index.ts";
export const app = express();
app.use(express.json());
const zodSchemaForSum = z.object({
a: z.number(),
b: z.number()
})
app.post("/sum",async (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
await prismaClient.sum.create({
data: {
a: parsedData.data.a,
b: parsedData.data.b,
result: answer
}
})
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
})
});
test/index.test.tsimport { describe, expect, it } from 'vitest';
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);
});
});
Notice how the tests begin to error out now

