Skip to content

Commit 1a52416

Browse files
committed
docs(drizzle): update
1 parent c457fe9 commit 1a52416

File tree

1 file changed

+62
-4
lines changed

1 file changed

+62
-4
lines changed

docs/content/3.recipes/3.drizzle.md

+62-4
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,9 @@ title: Drizzle
33
description:
44
---
55

6-
## Database
6+
## `useDB()`
77

8-
To enhance your development experience with databases, we recommand creating this type of composable:
9-
10-
### `useDB()`
8+
To enhance your DX with databases, we recommand using our pattern with `useDB()`:
119

1210
```ts
1311
import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'
@@ -31,3 +29,63 @@ export function useDB() {
3129
```
3230

3331
This allows you to conveniently reference your tables and interact directly with the [Drizzle API](https://orm.drizzle.team/docs/overview).
32+
33+
### Select
34+
35+
```ts[/api/todos/index.get.ts]
36+
export default eventHandler(async () => {
37+
const todos = await useDB().select().from(tables.todos).all()
38+
39+
return todos
40+
})
41+
```
42+
43+
### Insert
44+
45+
```ts[/api/todos/index.post.ts]
46+
export default eventHandler(async (event) => {
47+
const { title } = await readBody(event)
48+
49+
const todo = await useDB().insert(tables.todos).values({
50+
title,
51+
createdAt: new Date()
52+
}).returning().get()
53+
54+
return todo
55+
})
56+
```
57+
58+
### Update
59+
60+
```ts[/api/todos/[id].patch.ts]
61+
export default eventHandler(async (event) => {
62+
const { id } = getRouterParams(event)
63+
const { completed } = await readBody(event)
64+
65+
const todo = await useDB().update(tables.todos).set({
66+
completed
67+
}).where(eq(tables.todos.id, Number(id))).returning().get()
68+
69+
return todo
70+
})
71+
```
72+
73+
### Delete
74+
75+
```ts[/api/todos/[id].delete.ts]
76+
export default eventHandler(async (event) => {
77+
const { id } = getRouterParams(event)
78+
79+
const deletedTodo = await useDB().delete(tables.todos).where(and(
80+
eq(tables.todos.id, Number(id))
81+
)).returning().get()
82+
83+
if (!deletedTodo) {
84+
throw createError({
85+
statusCode: 404,
86+
message: 'Todo not found'
87+
})
88+
}
89+
return deletedTodo
90+
})
91+
```

0 commit comments

Comments
 (0)