Step 7 - Blog routes
Course: Blogging website - chapter 7
Better routing
Section titled “Better routing”https://hono.dev/api/routing#grouping
Hono let’s you group routes together so you can have a cleaner file structure.
Create two new files -
routes/user.ts
routes/blog.ts
and push the user routes to user.ts
index.ts
import { Hono } from 'hono'import { userRouter } from './routes/user';import { bookRouter } from './routes/blog';
export const app = new Hono<{ Bindings: { DATABASE_URL: string; JWT_SECRET: string; }}>();
app.route('/api/v1/user', userRouter)app.route('/api/v1/book', bookRouter)
export default appuser.ts
$1bBlog routes
Section titled “Blog routes”1. Create the route to initialize a blog/post
Section titled “1. Create the route to initialize a blog/post”Solution
app.post('/', async (c) => { const userId = c.get('userId'); const prisma = new PrismaClient({ datasourceUrl: c.env?.DATABASE_URL , }).$extends(withAccelerate());
const body = await c.req.json(); const post = await prisma.post.create({ data: { title: body.title, content: body.content, authorId: userId } }); return c.json({ id: post.id });})2. Create the route to update blog
Section titled “2. Create the route to update blog”Solution
app.put('/api/v1/blog', async (c) => { const userId = c.get('userId'); const prisma = new PrismaClient({ datasourceUrl: c.env?.DATABASE_URL , }).$extends(withAccelerate());
const body = await c.req.json(); prisma.post.update({ where: { id: body.id, authorId: userId }, data: { title: body.title, content: body.content } });
return c.text('updated post');});3. Create the route to get a blog
Section titled “3. Create the route to get a blog”Solution
app.get('/api/v1/blog/:id', async (c) => { const id = c.req.param('id'); const prisma = new PrismaClient({ datasourceUrl: c.env?.DATABASE_URL , }).$extends(withAccelerate());
const post = await prisma.post.findUnique({ where: { id } });
return c.json(post);})4. Create the route to get all blogs
Section titled “4. Create the route to get all blogs”Solution
app.get('/api/v1/blog/bulk', async (c) => { const prisma = new PrismaClient({ datasourceUrl: c.env?.DATABASE_URL , }).$extends(withAccelerate());
const posts = await prisma.post.find({});
return c.json(posts);})Try to hit the routes via POSTMAN and ensure they work as expected
