Build a Finance SaaS Platform -7 (Post Method)

Install drizzle-zod

1
2
npm i drizzle-zod
npm i @hono/zod-validator

Install cuid2

1
npm install --save @paralleldrive/cuid2

Add Post Method

Modify app/api/[[...route]]/accounts.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { createId } from "@paralleldrive/cuid2";
import { clerkMiddleware, getAuth } from "@hono/clerk-auth";

import {db} from "@/db/drizzle";
import {accounts, insertAccountSchema} from "@/db/schema";
import { eq } from "drizzle-orm";

const app = new Hono()
.get("/", clerkMiddleware(), async (c) => {
const auth = getAuth(c);

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

const data = await db.select({
id: accounts.id,
name: accounts.name,
}).from(accounts)
.where(eq(accounts.userId, auth.userId));

return c.json({ accounts: data });
})
.post(
"/",
clerkMiddleware(),
zValidator('json',insertAccountSchema.pick({
name:true,
})),
async(c) => {
const auth = getAuth(c);
const values = c.req.valid("json");

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

const data = await db.insert(accounts).values({
id: createId(),
userId: auth.userId,
...values,
}).returning();

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

export default app;

请我喝杯咖啡吧~

支付宝
微信