CRUD
This commit is contained in:
parent
74aaebf6b3
commit
81a9c13e73
4
.gitignore
vendored
4
.gitignore
vendored
|
@ -11,3 +11,7 @@
|
||||||
_fresh/
|
_fresh/
|
||||||
# npm dependencies
|
# npm dependencies
|
||||||
node_modules/
|
node_modules/
|
||||||
|
|
||||||
|
*.db
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
|
|
@ -1,12 +1,14 @@
|
||||||
import { JSX } from 'preact'
|
import { JSX } from 'preact'
|
||||||
import { IS_BROWSER } from '$fresh/runtime.ts'
|
import { IS_BROWSER } from '$fresh/runtime.ts'
|
||||||
|
|
||||||
export function Button(props: JSX.HTMLAttributes<HTMLButtonElement>) {
|
export function Button(
|
||||||
|
{ disabled, className, ...props }: JSX.HTMLAttributes<HTMLButtonElement>,
|
||||||
|
) {
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
{...props}
|
{...props}
|
||||||
disabled={!IS_BROWSER || props.disabled}
|
disabled={!IS_BROWSER || disabled}
|
||||||
class='px-2 py-1 bg-gray-500/20 rounded hover:bg-gray-500/25 cursor-pointer transition-colors'
|
class={`px-2 py-1 bg-gray-500/20 rounded hover:bg-gray-500/25 cursor-pointer transition-colors ${className}`}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
24
components/Input.tsx
Normal file
24
components/Input.tsx
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
import { JSX } from 'preact'
|
||||||
|
|
||||||
|
export function Input(
|
||||||
|
{ className, ...props }: JSX.HTMLAttributes<HTMLInputElement>,
|
||||||
|
) {
|
||||||
|
if (!props.id && props.name) {
|
||||||
|
props.id = props.name
|
||||||
|
} else if (!props.name && props.id) {
|
||||||
|
props.name = props.id
|
||||||
|
}
|
||||||
|
let defaultClassName =
|
||||||
|
'border-2 bg-stone-500/20 border-stone-500/20 px-2 py-1 rounded'
|
||||||
|
if (props.type == 'submit') {
|
||||||
|
defaultClassName =
|
||||||
|
'px-2 py-1 bg-emerald-500/20 rounded hover:bg-gray-500/25 cursor-pointer transition-colors'
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
{...props}
|
||||||
|
class={`${defaultClassName} ${className}`}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
11
components/Label.tsx
Normal file
11
components/Label.tsx
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
import { JSX } from 'preact'
|
||||||
|
|
||||||
|
export function Label(
|
||||||
|
{ children, className, ...props }: JSX.HTMLAttributes<HTMLLabelElement>,
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
<label {...props} class={`flex flex-col ${className}`} for='name'>
|
||||||
|
{children}
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
}
|
|
@ -1,37 +1,44 @@
|
||||||
import { Todo, UserWithTodos } from '@homeman/models.ts'
|
import { Todo, UserWithTodos } from '@homeman/models.ts'
|
||||||
|
import { Button } from '@homeman/components/Button.tsx'
|
||||||
|
|
||||||
export interface Props {
|
export interface Props {
|
||||||
user: UserWithTodos
|
user: UserWithTodos
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TodoList({ user: { avatarUrl, assignedTodos, name } }: Props) {
|
export function TodoList(
|
||||||
const todoItem = ({ description }: Todo) => (
|
{ user: { avatarUrl, assignedTodos, name, color } }: Props,
|
||||||
<li class='bg-white dark:bg-black drop-shadow-xl'>{description}</li>
|
) {
|
||||||
|
const todoItem = (
|
||||||
|
{ classList, description }: Pick<Todo, 'description'> & {
|
||||||
|
classList?: string
|
||||||
|
},
|
||||||
|
) => (
|
||||||
|
<li
|
||||||
|
style={`border-color: #${color}`}
|
||||||
|
class={`${
|
||||||
|
classList || ''
|
||||||
|
} border-l-4 p-4 rounded drop-shadow-lg bg-white dark:bg-stone-900 flex flex-col`}
|
||||||
|
>
|
||||||
|
<span class='text-xl'>{description}</span>
|
||||||
|
<Button class='mt-2'>Done</Button>
|
||||||
|
</li>
|
||||||
)
|
)
|
||||||
return (
|
return (
|
||||||
<div class='p-2 w-1/4 min-w-[10rem] relative flex flex-col grow-0'>
|
<div class='p-2 w-1/4 min-w-[15rem] relative flex flex-col grow-0'>
|
||||||
{avatarUrl != null
|
|
||||||
? (
|
|
||||||
<img
|
<img
|
||||||
class='rounded-full w-full mb-2'
|
class='rounded-full w-full mb-2'
|
||||||
src={avatarUrl}
|
src={avatarUrl != null ? avatarUrl : 'https://placehold.co/512x512'}
|
||||||
title={`${name}'s avatar`}
|
title={`${name}'s avatar`}
|
||||||
/>
|
/>
|
||||||
)
|
|
||||||
: null}
|
|
||||||
<span class='text-sky-800 dark:text-sky-200 font-semibold text-center'>
|
<span class='text-sky-800 dark:text-sky-200 font-semibold text-center'>
|
||||||
{name}
|
{name}
|
||||||
</span>
|
</span>
|
||||||
<button class='mt-4 mb-4 text-left w-full px-2 py-1 rounded-lg border-[1px] text-stone-500 border-stone-500 opacity-50 hover:opacity-100'>
|
<button class='mt-4 mb-4 text-left w-full px-2 py-1 rounded-lg border-[1px] text-stone-500 border-stone-500 opacity-50 hover:opacity-100'>
|
||||||
+ New
|
+ New
|
||||||
</button>
|
</button>
|
||||||
<ul class=''>
|
<ul class='flex flex-col gap-y-4'>
|
||||||
{assignedTodos.length < 1
|
{assignedTodos.length < 1
|
||||||
? (
|
? todoItem({ description: 'All clear! 🎉', classList: 'text-center' })
|
||||||
<li class='p-4 rounded-lg text-center drop-shadow-xl bg-white dark:bg-stone-900'>
|
|
||||||
All clear! 🎉
|
|
||||||
</li>
|
|
||||||
)
|
|
||||||
: assignedTodos.map(todoItem)}
|
: assignedTodos.map(todoItem)}
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
47
crud.ts
Normal file
47
crud.ts
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
import { Handlers } from '$fresh/server.ts'
|
||||||
|
import { ulid } from 'https://deno.land/x/ulid@v0.3.0/mod.ts'
|
||||||
|
import { type AnyZodObject } from 'https://deno.land/x/zod@v3.21.4/mod.ts'
|
||||||
|
import { db } from '@homeman/models.ts'
|
||||||
|
|
||||||
|
export function crudHandler<
|
||||||
|
SchemaName extends keyof typeof db,
|
||||||
|
Schema = db[SchemaName
|
||||||
|
CreateSchema extends AnyZodObject,
|
||||||
|
Creator extends (s: CreateSchema) => Promise<Schema>,
|
||||||
|
>(
|
||||||
|
schema: SchemaName,
|
||||||
|
createModel: CreateSchema,
|
||||||
|
creator: Creator,
|
||||||
|
): Handlers<typeof db[SchemaName]Schema | null> {
|
||||||
|
return {
|
||||||
|
async POST(req, _ctx) {
|
||||||
|
const data = createModel.parse(await req.json())
|
||||||
|
const newModel: typeof db[SchemaName] = await creator(
|
||||||
|
data as CreateSchema,
|
||||||
|
)
|
||||||
|
const result = await db[schema].create({ data: newModel })
|
||||||
|
return new Response(JSON.stringify(result))
|
||||||
|
},
|
||||||
|
async PUT(req, _ctx) {
|
||||||
|
const user = UserModel.parse(await req.json())
|
||||||
|
const result = await db.users.update({ data: user })
|
||||||
|
return new Response(JSON.stringify(result))
|
||||||
|
},
|
||||||
|
async DELETE(req, _ctx) {
|
||||||
|
const userData = UserModel.pick({ id: true }).parse(await req.json())
|
||||||
|
const result = await db.users.delete({ where: userData })
|
||||||
|
return new Response(JSON.stringify(result))
|
||||||
|
},
|
||||||
|
async GET(req, _ctx) {
|
||||||
|
const data = await req.json().catch(() => {})
|
||||||
|
const userData = UserModel.pick({ id: true }).safeParse(data)
|
||||||
|
if (userData.success) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify(await db.users.findFirst({ where: userData.data })),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
return new Response(JSON.stringify(await db.users.findMany({})))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
|
@ -14,6 +14,7 @@
|
||||||
deno-dev = pkgs.mkShell {
|
deno-dev = pkgs.mkShell {
|
||||||
buildInputs = with pkgs; [
|
buildInputs = with pkgs; [
|
||||||
deno
|
deno
|
||||||
|
xh
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -6,6 +6,8 @@ import * as $_404 from './routes/_404.tsx'
|
||||||
import * as $_app from './routes/_app.tsx'
|
import * as $_app from './routes/_app.tsx'
|
||||||
import * as $admin from './routes/admin.tsx'
|
import * as $admin from './routes/admin.tsx'
|
||||||
import * as $api_joke from './routes/api/joke.ts'
|
import * as $api_joke from './routes/api/joke.ts'
|
||||||
|
import * as $api_todo from './routes/api/todo.ts'
|
||||||
|
import * as $api_user from './routes/api/user.ts'
|
||||||
import * as $greet_name_ from './routes/greet/[name].tsx'
|
import * as $greet_name_ from './routes/greet/[name].tsx'
|
||||||
import * as $index from './routes/index.tsx'
|
import * as $index from './routes/index.tsx'
|
||||||
import * as $Admin from './islands/Admin.tsx'
|
import * as $Admin from './islands/Admin.tsx'
|
||||||
|
@ -19,6 +21,8 @@ const manifest = {
|
||||||
'./routes/_app.tsx': $_app,
|
'./routes/_app.tsx': $_app,
|
||||||
'./routes/admin.tsx': $admin,
|
'./routes/admin.tsx': $admin,
|
||||||
'./routes/api/joke.ts': $api_joke,
|
'./routes/api/joke.ts': $api_joke,
|
||||||
|
'./routes/api/todo.ts': $api_todo,
|
||||||
|
'./routes/api/user.ts': $api_user,
|
||||||
'./routes/greet/[name].tsx': $greet_name_,
|
'./routes/greet/[name].tsx': $greet_name_,
|
||||||
'./routes/index.tsx': $index,
|
'./routes/index.tsx': $index,
|
||||||
},
|
},
|
||||||
|
|
|
@ -1,6 +1,8 @@
|
||||||
import { createRef } from 'preact'
|
import { createRef } from 'preact'
|
||||||
import { Todo, User } from '@homeman/models.ts'
|
import { Todo, User } from '@homeman/models.ts'
|
||||||
import { Button } from '@homeman/components/Button.tsx'
|
import { Button } from '@homeman/components/Button.tsx'
|
||||||
|
import { Input } from '@homeman/components/Input.tsx'
|
||||||
|
import { Label } from '@homeman/components/Label.tsx'
|
||||||
|
|
||||||
export interface Props {
|
export interface Props {
|
||||||
users: User[]
|
users: User[]
|
||||||
|
@ -15,7 +17,42 @@ export function Admin({ users, todos }: Props) {
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<main class='flex flex-col'>
|
<main class='flex flex-col'>
|
||||||
<dialog ref={addUserDialog}>sup</dialog>
|
<dialog
|
||||||
|
class='rounded drop-shadow-lg backdrop:bg-stone-500/90'
|
||||||
|
ref={addUserDialog}
|
||||||
|
>
|
||||||
|
<header class='p-4 flex w-full items-center border-b-2 border-stone-500/20'>
|
||||||
|
<h1 class='text-xl grow'>Add user</h1>
|
||||||
|
<Button
|
||||||
|
onClick={() => addUserDialog.current?.close()}
|
||||||
|
class='text-xl p-4 border-b-2 mr-4'
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</Button>
|
||||||
|
</header>
|
||||||
|
<form class='p-4 gap-4 flex flex-col' action='/api/user' method='post'>
|
||||||
|
<Label for='name'>
|
||||||
|
Name
|
||||||
|
<Input autofocus name='name' />
|
||||||
|
</Label>
|
||||||
|
<Label for='avatar'>
|
||||||
|
Avatar
|
||||||
|
<Input type='file' name='avatar' />
|
||||||
|
</Label>
|
||||||
|
<Label for='color'>
|
||||||
|
Color
|
||||||
|
<Input type='color' name='color' />
|
||||||
|
</Label>
|
||||||
|
<footer class='flex justify-end gap-2'>
|
||||||
|
<Button
|
||||||
|
onClick={() => addUserDialog.current?.close()}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Input type='submit' value='Save' />
|
||||||
|
</footer>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
<header class='flex items-center border-b-2 border-stone-500/20 '>
|
<header class='flex items-center border-b-2 border-stone-500/20 '>
|
||||||
<h1 class='p-5 text-2xl'>
|
<h1 class='p-5 text-2xl'>
|
||||||
Users ({users.length})
|
Users ({users.length})
|
||||||
|
@ -37,9 +74,11 @@ export function Admin({ users, todos }: Props) {
|
||||||
<tr>
|
<tr>
|
||||||
<td>{name}</td>
|
<td>{name}</td>
|
||||||
<td>
|
<td>
|
||||||
{avatarUrl == null ? 'None' : <img class='' src={avatarUrl} />}
|
{avatarUrl == null
|
||||||
|
? 'None'
|
||||||
|
: <img class='h-16 w-16' src={avatarUrl} />}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td style={`color: #${color}`}>
|
||||||
#{color}
|
#{color}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
|
@ -2,7 +2,7 @@ import { z } from 'https://deno.land/x/zod@v3.21.4/mod.ts'
|
||||||
import { createPentagon } from 'https://deno.land/x/pentagon@v0.1.5/mod.ts'
|
import { createPentagon } from 'https://deno.land/x/pentagon@v0.1.5/mod.ts'
|
||||||
// import { ulid } from 'https://deno.land/x/ulid@v0.3.0/mod.ts'
|
// import { ulid } from 'https://deno.land/x/ulid@v0.3.0/mod.ts'
|
||||||
|
|
||||||
const kv = await Deno.openKv()
|
const kv = await Deno.openKv('homeman.db')
|
||||||
|
|
||||||
// const todos = kv.list({ prefix: ['todos'] })
|
// const todos = kv.list({ prefix: ['todos'] })
|
||||||
// const deleteme = []
|
// const deleteme = []
|
||||||
|
@ -22,6 +22,7 @@ const User = z.object({
|
||||||
avatarUrl: z.string().nullable(),
|
avatarUrl: z.string().nullable(),
|
||||||
color: z.string().nullable(),
|
color: z.string().nullable(),
|
||||||
})
|
})
|
||||||
|
export const UserModel = User
|
||||||
export type User = z.infer<typeof User>
|
export type User = z.infer<typeof User>
|
||||||
export type UserWithTodos = User & {
|
export type UserWithTodos = User & {
|
||||||
assignedTodos: Todo[]
|
assignedTodos: Todo[]
|
||||||
|
@ -37,6 +38,7 @@ const Todo = z.object({
|
||||||
doneAt: z.date().nullable(),
|
doneAt: z.date().nullable(),
|
||||||
assigneeUserId: z.string().ulid().nullable(),
|
assigneeUserId: z.string().ulid().nullable(),
|
||||||
})
|
})
|
||||||
|
export const TodoModel = Todo
|
||||||
export type Todo = z.infer<typeof Todo>
|
export type Todo = z.infer<typeof Todo>
|
||||||
|
|
||||||
export const db = createPentagon(kv, {
|
export const db = createPentagon(kv, {
|
||||||
|
|
35
routes/api/todo.ts
Normal file
35
routes/api/todo.ts
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
import { Handlers } from '$fresh/server.ts'
|
||||||
|
import { db, Todo, TodoModel } from '@homeman/models.ts'
|
||||||
|
import { ulid } from 'https://deno.land/x/ulid@v0.3.0/mod.ts'
|
||||||
|
|
||||||
|
const TodoCreate = TodoModel.omit({ id: true, createdAt: true })
|
||||||
|
|
||||||
|
export const handler: Handlers<Todo | null> = {
|
||||||
|
async POST(req, _ctx) {
|
||||||
|
const todo = TodoCreate.parse(await req.json())
|
||||||
|
const newTodo: Todo = { ...todo, id: ulid(), createdAt: new Date() }
|
||||||
|
const result = await db.todos.create({ data: newTodo })
|
||||||
|
return new Response(JSON.stringify(result))
|
||||||
|
},
|
||||||
|
async PUT(req, _ctx) {
|
||||||
|
const todo = TodoModel.parse(await req.json())
|
||||||
|
const result = await db.todos.update({ data: todo })
|
||||||
|
return new Response(JSON.stringify(result))
|
||||||
|
},
|
||||||
|
async DELETE(req, _ctx) {
|
||||||
|
const todoData = TodoModel.pick({ id: true }).parse(await req.json())
|
||||||
|
const result = await db.todos.delete({ where: todoData })
|
||||||
|
return new Response(JSON.stringify(result))
|
||||||
|
},
|
||||||
|
async GET(req, _ctx) {
|
||||||
|
const data = await req.json().catch(() => {})
|
||||||
|
const todoData = TodoModel.pick({ id: true }).safeParse(data)
|
||||||
|
if (todoData.success) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify(await db.todos.findFirst({ where: todoData.data })),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
return new Response(JSON.stringify(await db.todos.findMany({})))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
37
routes/api/user.ts
Normal file
37
routes/api/user.ts
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
import { Handlers } from '$fresh/server.ts'
|
||||||
|
import { db, User, UserModel } from '@homeman/models.ts'
|
||||||
|
import { ulid } from 'https://deno.land/x/ulid@v0.3.0/mod.ts'
|
||||||
|
|
||||||
|
const UserCreate = UserModel.omit({ id: true, createdAt: true })
|
||||||
|
|
||||||
|
export const handler: Handlers<User | null> = {
|
||||||
|
async POST(req, _ctx) {
|
||||||
|
const formData = await req.formData()
|
||||||
|
console.log('user form data POSTed', formData)
|
||||||
|
const user = UserCreate.parse(formData)
|
||||||
|
const newUser: User = { ...user, id: ulid(), createdAt: new Date() }
|
||||||
|
const result = await db.users.create({ data: newUser })
|
||||||
|
return new Response(JSON.stringify(result))
|
||||||
|
},
|
||||||
|
async PUT(req, _ctx) {
|
||||||
|
const user = UserModel.parse(await req.json())
|
||||||
|
const result = await db.users.update({ data: user })
|
||||||
|
return new Response(JSON.stringify(result))
|
||||||
|
},
|
||||||
|
async DELETE(req, _ctx) {
|
||||||
|
const userData = UserModel.pick({ id: true }).parse(await req.json())
|
||||||
|
const result = await db.users.delete({ where: userData })
|
||||||
|
return new Response(JSON.stringify(result))
|
||||||
|
},
|
||||||
|
async GET(req, _ctx) {
|
||||||
|
const data = await req.json().catch(() => {})
|
||||||
|
const userData = UserModel.pick({ id: true }).safeParse(data)
|
||||||
|
if (userData.success) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify(await db.users.findFirst({ where: userData.data })),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
return new Response(JSON.stringify(await db.users.findMany({})))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
|
@ -37,7 +37,7 @@ export default function Home(
|
||||||
<h1 class='p-5 border-b-2 border-stone-500/20 text-2xl'>
|
<h1 class='p-5 border-b-2 border-stone-500/20 text-2xl'>
|
||||||
Todos
|
Todos
|
||||||
</h1>
|
</h1>
|
||||||
<ul class='p-4 relative'>
|
<ul class='p-4 relative flex'>
|
||||||
<li>
|
<li>
|
||||||
<TodoList user={unassignedUser} />
|
<TodoList user={unassignedUser} />
|
||||||
</li>
|
</li>
|
||||||
|
|
|
@ -2,5 +2,9 @@
|
||||||
@tailwind components;
|
@tailwind components;
|
||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
|
|
||||||
|
dialog {
|
||||||
|
@apply bg-stone-100 text-stone-950 dark:bg-stone-950 dark:text-stone-100;
|
||||||
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue