Skip to content

Step 7 - Blog routes

Course: Blogging website - chapter 7

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 app
user.ts
$1b

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
});
})
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');
});
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);
})
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