🦁

【Drizzle ORM】NextJs14 と Drizzle ORM【#29 Profile Route】

2024/11/15に公開

【#29 Profile Route】

YouTube: https://youtu.be/YqABGH4lzs0
https://youtu.be/YqABGH4lzs0

今回は「Profile」用のルートを作成していきます。

「api」フォルダ内の[[...route]]フォルダ内に
「profiles.ts」を作成します。

app/api/[[...route]]/profiles.ts
import { Hono } from "hono";
import { z } from "zod";
import { zValidator } from "@hono/zod-validator";
import { clerkMiddleware, getAuth } from "@hono/clerk-auth";
import { eq } from "drizzle-orm";
import { createId } from "@paralleldrive/cuid2";

import { db } from "@/db/drizzle";
import { profile, users } from "@/db/schema";

const app = new Hono().post(
  "/",
  clerkMiddleware(),
  zValidator(
    "json",
    z.object({
      message: z.string(),
    })
  ),
  async (c) => {
    const auth = getAuth(c);
    const { message } = c.req.valid("json");

    if (!auth?.userId) {
      return c.json({ error: "Unauthorized" }, 401);
    }

    const user = await db.query.users.findFirst({
      where: eq(users.clerkId, auth.userId),
    });

    if (!user) {
      return c.json({ error: "This user not found" }, 404);
    }

    const [data] = await db
      .insert(profile)
      .values({
        id: createId(),
        userId: user.id,
        message: message,
      })
      .returning();

    return c.json({ data });
  }
);

export default app;

Discussion