Full-stack Web Technologies

CHAPTER 4
Endpoints for one Entity

  1. Create a file db.ts with just the code that creates the PrismaClient and export it so that the whole server has access to it as db.

  2. 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" });
      }
    });
    
  3. Create a new endpoint in Thunder Client to test that it works.

Move forums to a new file.

  1. Create a new file forums.ts that will contain the forum's endpoints.

  2. 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" });
      }
    });
    
  3. Import the forums.ts file and use it in the server.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 in forums.ts.

  4. Write down (as a comment in the code) what are the endpoints that the API should implement:

    MethodPathFunction
    GET/forums/Get all forums
    GET/forums/:idGet one forum
    POST/forumsAdd one forum
    PUT/forums/:idUpdate one forum
    DELETE/forums/:idDelete one forum
    GET/forums/:id/messagesGet all message in a forum
    POST/forums/:id/messagesAdd a message to a forum
  5. Add the test for the /forums/:id in the API tester. Check that it gives a 404 error.

  6. 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(),
        });
      }
    });