PioneerSquareLabs / otto-playground

A playground where Otto can run free while hopefully not accidentally reformatting your hard drive
https://otto-playground.vercel.app
13 stars 0 forks source link

Create API endpoint => src/pages/api/projects.ts #714

Closed otto-jacob closed 1 year ago

otto-jacob commented 1 year ago

Create the API endpoint src/pages/api/projects.ts. Here is the description: Next.js API route for projects. Be sure to add the proper extension when creating the file. Here are the instructions:

Issue Description

In this issue, we will create a Next.js API route for managing projects. The API route will be located at src/pages/api/projects.ts. This route will handle the following actions:

Step-by-step Instructions

  1. Create a new file named projects.ts inside the src/pages/api directory.

  2. Import the necessary modules and types:

import { NextApiRequest, NextApiResponse } from "next";
import { Prisma } from "@prisma/client";
import { z } from "zod";
import { prisma } from "~/server/db";
import { getServerAuthSession } from "~/server/auth";
import { User, Project, projectSchema } from "~/src/types";
  1. Define the handler function with the following signature:
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  // Implementation goes here
};
  1. Inside the handler function, call getServerAuthSession({ req, res }) to retrieve the user's session. If there is no session, return a 401 Unauthorized status code and an error message:
const session = await getServerAuthSession({ req, res });
if (!session) {
  res.status(401).json({ error: "Unauthorized" });
  return;
}
  1. Now, handle the different request methods (GET and POST) using a switch statement:
switch (req.method) {
  case "GET":
    // Handle GET requests
    break;
  case "POST":
    // Handle POST requests
    break;
  default:
    res.setHeader("Allow", ["GET", "POST"]);
    res.status(405).end(`Method ${req.method} Not Allowed`);
}
  1. For the GET case, query the database to retrieve all projects for the authenticated user:
const projects = await prisma.project.findMany({
  where: { userId: session.user.id },
});
  1. Validate the retrieved projects using the projectSchema from the types.ts file:
const validatedProjects = projects.map((project) => projectSchema.parse(project));
  1. Return the validated projects as a JSON response:
res.status(200).json(validatedProjects);
  1. For the POST case, first, validate the request body using a Zod schema:
const createProjectSchema = z.object({
  name: z.string(),
  description: z.string(),
});

const { name, description } = createProjectSchema.parse(req.body);
  1. Create a new project in the database for the authenticated user:
const newProject = await prisma.project.create({
  data: {
    name,
    description,
    userId: session.user.id,
  },
});
  1. Validate the created project using the projectSchema from the types.ts file:
const validatedProject = projectSchema.parse(newProject);
  1. Return the validated project as a JSON response:
res.status(201).json(validatedProject);
  1. Finally, export the handler function as the default export:
export default handler;

Summary

In this issue, we created a Next.js API route for managing projects at src/pages/api/projects.ts. The route supports GET and POST methods for retrieving a list of projects and creating a new project for the authenticated user. We used the getServerAuthSession function for authentication, Prisma for database interaction, and Zod for data validation.