API call — Ship Fast ⚡️

Here's what your code would look like on NextJS /api routes. Example: PATCH /edit-name {name: "Marclou"}

/api/edit-name.ts


import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import connectMongo from "@/libs/mongoose";
import User from "@/models/User";

export default async function handler(req, res) {
  // Parse the cookies and check if user is authenticated.
  const session = await getServerSession(req, res, authOptions);

  if (session) {
    const { id } = session.user;
    const { method, body } = req;

    await connectMongo();

    switch (method) {
      case "PATCH": {
        if (!body || !body.name) {
          return res.status(404).send({
            error: "Need a user name to update",
          });
        }

        try {
          const user = await User.findById(id);

          if (!user) {
            return res.status(404).send({ error: "User not found" });
          }

          user.name = body.name;

          await user.save();

          return res.status(200).json({});
        } catch (e) {
          console.error(e?.message);
          return res.status(500).json({ error: e?.message });
        }
      }

      default:
        return res.status(404).json({ error: "Unknow request type" });
    }
  } else {
    // Not Signed in
    // apiClient (in /libs/api.js) will automatically redirect to login page
    res.status(401).end();
  }
}