Last active
June 30, 2024 10:16
-
-
Save yusukebe/2b56098f35b5b2660627d85581dac125 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { count, desc, eq } from 'drizzle-orm' | |
import { createAction } from 'hono/action' | |
import { showRoutes } from 'hono/dev' | |
import { likes, posts } from '../db/schema' | |
import adminApp from './admin/index' | |
import { factory } from './factory' | |
import { useRequestContext } from 'hono/jsx-renderer' | |
const app = factory.createApp() | |
app.route('/', adminApp) | |
const LikeButton = async ({ postId }: { postId: number }) => { | |
const c = useRequestContext() | |
const result = await c.var.db | |
.select({ count: count() }) | |
.from(likes) | |
.where(eq(likes.postId, postId)) | |
return ( | |
<> | |
<input type='hidden' name='postId' value={postId} /> | |
<button>{result[0].count} likes</button> | |
</> | |
) | |
} | |
const [action] = createAction(app, async (data, c, { children }) => { | |
if (data) { | |
await c.var.db.insert(likes).values({ | |
postId: data.postId, | |
}) | |
} | |
return children | |
}) | |
app.get('/', async (c) => { | |
const result = await c.var.db | |
.select() | |
.from(posts) | |
.orderBy(desc(posts.createdAt)) | |
return c.render( | |
<section> | |
{result.map((post, index) => { | |
return ( | |
<aside> | |
<h2>{post.title}</h2> | |
<div>{post.body}</div> | |
<form action={action(index)}> | |
<LikeButton postId={post.id} /> | |
</form> | |
</aside> | |
) | |
})} | |
</section> | |
) | |
}) | |
showRoutes(app) | |
export default app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment