👻

【NextJs + ElysiaJs】NexJs&ElysiaJs【#8 Posts Route】

に公開

【#8 Posts Route】
YouTube: https://youtu.be/XptO2Wrh74Q
https://youtu.be/XptO2Wrh74Q

今回はPosts用のルートを作成します。

server/routes/posts.ts
import { Elysia, t } from "elysia";
import { and, eq } from "drizzle-orm";

import { db } from "@/src";
import { posts } from "@/src/db/schema";

import { betterAuth } from "../protected-route";

export const postsRouter = new Elysia({ prefix: "/posts" })
  .use(betterAuth)
  .get("/", async () => {
    const postsData = await db.select().from(posts);

    if (!postsData) {
      throw new Response("Posts not found", { status: 404 });
    }

    return postsData;
  })
  .get(
    "/:id",
    async ({ params }) => {
      const { id } = params;

      const [post] = await db.select().from(posts).where(eq(posts.id, id));

      if (!post) {
        throw new Response("Post not found", { status: 404 });
      }

      return post;
    },
    {
      params: t.Object({
        id: t.String(),
      }),
    }
  )
  .post(
    "/",
    async ({ body, session }) => {
      const { name, content } = body;
      const { id: userId } = session.user;

      const [data] = await db
        .insert(posts)
        .values({
          name,
          content,
          userId,
        })
        .returning();

      if (!data) {
        throw new Response("Internal Error", { status: 500 });
      }

      return data;
    },
    {
      //todo: add body type
      auth: true,
    }
  )
  .patch(
    "/:id",
    async ({ params, body, session }) => {
      const { id } = params;
      const { name, content } = body;
      const { id: userId } = session.user;

      const [updatedPost] = await db
        .update(posts)
        .set({
          name,
          content,
        })
        .where(and(eq(posts.id, id), eq(posts.userId, userId)))
        .returning();

      if (!updatedPost) {
        throw new Response("Post not found", { status: 404 });
      }

      return updatedPost;
    },
    {
      //todo: add body type
      auth: true,
      params: t.Object({
        id: t.String(),
      }),
    }
  )
  .delete(
    "/:id",
    async ({ params, session }) => {
      const { id } = params;
      const { id: userId } = session.user;

      const [deletedPost] = await db
        .delete(posts)
        .where(and(eq(posts.id, id), eq(posts.userId, userId)))
        .returning();

      if (!deletedPost) {
        throw new Response("Post not found", { status: 404 });
      }

      return deletedPost;
    },
    {
      auth: true,
      params: t.Object({
        id: t.String(),
      }),
    }
  );

app/api/[[...slugs]]/route.ts
import { Elysia } from "elysia";
import { cors } from "@elysiajs/cors";

import { helloRouter } from "@/server/routes/hello";
import { postsRouter } from "@/server/routes/posts";

export const app = new Elysia({ prefix: "/api" })
  .use(
    cors({
      origin:
        process.env.NODE_ENV === "production"
          ? process.env.NEXT_PUBLIC_APP_URL
          : true,
      methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
      credentials: true,
      allowedHeaders: ["Content-Type", "Authorization", "Cookie"],
      exposeHeaders: ["Set-Cookie"],
    })
  )
  .use(helloRouter)
  .use(postsRouter);

export const GET = app.fetch;
export const POST = app.fetch;
export const PUT = app.fetch;
export const PATCH = app.fetch;
export const DELETE = app.fetch;
export const OPTIONS = app.fetch;

Discussion