CHAPTER 4Endpoints for one Entity
-
Create a file
db.ts
with just the code that creates thePrismaClient
and export it so that the whole server has access to it asdb
. -
Create a new endpoint after the
GET /
one with code like this:app.get("/forums", async (req, res) => { try { const result = await db.forum.findMany({}); res.status(200).json(result); } catch (e) { res.status(500).json({ error: "Internal error" }); } });
-
Create a new endpoint in Thunder Client to test that it works.
Move forums
to a new file.
-
Create a new file
forums.ts
that will contain the forum's endpoints. -
Move the endpoint created in the server so that it looks like this:
import { Router } from "express"; import db from "./db"; export const forums = Router(); forums.get("/", async (req, res) => { try { const result = await db.forum.findMany({}); res.status(200).json(result); } catch (e) { res.status(500).json({ error: "Internal error" }); } });
-
Import the
forums.ts
file and use it in theserver.ts
file:import { forums } from "./forums";
and
app.use("/forums", forums);
Check that this change didn't brake anything. It should work as before but now the
/forums
endpoints are all inforums.ts
. -
Write down (as a comment in the code) what are the endpoints that the API should implement:
Method Path Function GET
/forums/
Get all forums GET
/forums/:id
Get one forum POST
/forums
Add one forum PUT
/forums/:id
Update one forum DELETE
/forums/:id
Delete one forum GET
/forums/:id/messages
Get all message in a forum POST
/forums/:id/messages
Add a message to a forum -
Add the test for the
/forums/:id
in the API tester. Check that it gives a 404 error. -
Implement the endpoint as:
forums.get("/:id", async (req, res) => { const { id } = req.params; try { const result = await db.forum.findFirst({ where: { forumId: Number(id) }, }); if (result === null) { return res.status(404).json({ error: `Forum with ID = ${id} not found`, }); } return res.status(200).send(result); } catch (e: any) { res.status(500).json({ type: e.constructor.name, message: e.toString(), }); } });