Mastering Hono: Simple Steps with Bun

Saurabh TailorSaurabh Tailor
2 min read

What is Hono ? Another JS framework ? can say so but it is so powerful , once u get hands on this framework u are not goin back to express.

It is a JS library , mostly used in Serverless architecture.

💡
what is serverless architecture and why u need it ?

Serverless architecture differs from traditional architectures in several key ways:-

  1. Auto-scaling: The platform automatically scales resources based on demand.

  2. Pay-per-use pricing: Users are charged only for the actual compute time used.

  3. Stateless functions: Each function execution is independent and stateless.

Examples of serverless architecture:

👉Aws Lambda

👉Cloudflare Worker

👉Edge Environement

Using Bun + Hono

to create Your App

bun create hono my-app

Now, how to use Hono for handling HTTP requests?

GET Request


app.get("/" , (c)=>{
    return c.text("working")
})

POST Request

app.post("/post" , async(c)=>{
    const {username , email , password} = await c.req.json()
    console.log(username , email , password);

    const user = {
        id:uuidv4(),
        username,
        email , 
        password
    }

    userDB.push(user)
    return c.json(user) //we dont need c.res.json()8+-\] 

})

Now One of the latest Bit in technology as u have seen in ChatGPT as well , that the data is streamed word by word or line by line , well guess what ? You can do similar in hono , isnt it awesome ?

app.get("/posts" , async(c)=>{
    return streamText(c , async(stream)=>{
        for(let user of userDB){ //userDB is an array of objects
            await stream.write(JSON.stringify(user))
            await stream.sleep(1000)
        }
    })
})

Q. How to get Param ?

app.get("/posts/:id" , (c)=>{
    const id = c.req.param("id") // it is param , not params
    console.log(id);
    console.log(userDB);
    const post = userDB.find((post)=> post.id === id)
    if(!post){
        return c.json({msg:"Video doesnt exist with that id"})
    }

    return c.text(JSON.stringify(post))
})

Connecting Hono With Our Database

Though it is a bit different with Both SQL and NoSql Databases

we are moving forward with NoSQL(MongoDB)

  1. Create a Model
import mongoose, { model, models, Schema } from "mongoose";

export interface Posts{
    _id: mongoose.Schema.Types.ObjectId;
    title: string;
    content: string;
}


const postSchema = new Schema<Posts>({
    title: {type: String, required: true},
    content: {type: String, required: true},
})

export  const Post = mongoose.models.Post || model<Posts>("Post" , postSchema)
  1. Connect To DB

     import mongoose from "mongoose";
    
     const connectToDB = async()=>{
         try {
             const connection = await mongoose.connect(String(process.env.MONGO_URI))
             console.log("DB is connected on::"+connection.connection.host);
    
         } catch (error) {
    
         }
     }
    
     export {connectToDB}
    
0
Subscribe to my newsletter

Read articles from Saurabh Tailor directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Saurabh Tailor
Saurabh Tailor