Last active
June 30, 2024 10:19
-
-
Save yusukebe/1cc93be73af7e7f112a47a1e23ec6543 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 { createForm } 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 [Form] = createForm(app, async (data, c) => { | |
if (data) { | |
await c.var.db.insert(likes).values({ | |
postId: data.postId, | |
}) | |
} | |
}) | |
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> | |
<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