🍣

【Drizzle ORM】NextJs14 と Drizzle ORM【#9 Hono Routing 】

2024/07/24に公開

【#9 Hono Routing 】

YouTube: https://youtu.be/mlmDJrL5oDM
https://youtu.be/mlmDJrL5oDM

今回はHonoのAPIに「users」のRouteを追加します。

https://hono.dev/docs/api/routing

こちらのファイルのconfigの部分があるとエラーがでますので、
一度コメントアウトにしておきます。

db/drizzle.ts
import { drizzle } from "drizzle-orm/neon-http";
import { neon } from "@neondatabase/serverless";
// import { config } from "dotenv";
import * as schema from "./schema";

// config({ path: ".env.local" });

const sql = neon(process.env.DATABASE_URL!);
export const db = drizzle(sql, { schema });
app/api/[[...route]]/route.ts
import { Hono } from "hono";
import { handle } from "hono/vercel";

import users from "./users";

export const runtime = "edge";

const app = new Hono().basePath("/api");

//http://localhost:3000/api/hello

app.get("/hello", (c) => {
  return c.json({
    message: "Hello Next.js!",
  });
});

app.route("/users", users);

export const GET = handle(app);
export const POST = handle(app);
export const PATCH = handle(app);
export const DELETE = handle(app);
app/api/[[...route]]/users.ts
import { Hono } from "hono";

import { db } from "@/db/drizzle";
import { users } from "@/db/schema";
import { eq } from "drizzle-orm";

const app = new Hono();

app.get("/", async (c) => {
  const data = await db.select().from(users);

  return c.json({
    users: data,
  });
});

app.get("/:id", async (c) => {
  const id = c.req.param("id");

  const data = await db.select().from(users).where(eq(users.id, id));

  return c.json({
    user: data,
  });
});

export default app;

Discussion