Ahmed Sadman Muhib
Ahmed Sadman Muhib

Reputation: 2438

How to wait for DB connection in a Hono/Bun application using Drizzle ORM?

As part of learning Hono and Drizzle, I'm creating a simple Web Server with Bun.

// src/index.ts
import { Hono } from "hono";
import UserRepo from "./repo/UserRepo";

const app = new Hono();

app.get("/ping", (c) => {
    return c.text("pong");
});

app.post("/user", async (c) => {
    const { name, email } = await c.req.json();
    const newUser = await UserRepo.create({ name, email });
    return c.json(newUser, 201);
});

app.onError((err, c) => {
    console.log(err);
    return c.json(err, 500);
});

export default {
    ...app,
    port: process.env.PORT || 3000,
};

And I have this DB, which is getting used through UserRepo. To keep it simple, I'm showing only the relevant DB code

// src/db/index.ts
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";

const queryClient = postgres(process.env.DB_URL as string);
const db = drizzle(queryClient);

export { db };

It works as expected. But the server doesn't wait for database connection. In Express, we could do something like mongoose.connect(...).then(() => app.listen(...)), I'm trying to do something similar with this application. Searched through the Docs but could not find anything. Any help would be highly appreciated.

Upvotes: 0

Views: 1163

Answers (2)

David Aprilio
David Aprilio

Reputation: 1

I solved with this

async function main() {
    try {
        await AppDataSource.initialize()
    } catch (error: any) {
        console.error(error);
        return process.exit(1)
    }

    Bun.serve({
        port: ENV.APP_PORT,
        fetch: app.fetch,
        
    })
    console.log(`Listening on port ${ENV.APP_HOST}:${ENV.APP_PORT}`);    
}
main()

Upvotes: 0

Nico Plyley
Nico Plyley

Reputation: 102

You can achieve what you’re trying to do with Bun.serve

dbConnect()
  .then(() => {
    Bun.serve(app);
    console.log('Server Running');
  })
  .catch((error) => {
    console.error(error);
  });

Upvotes: 0

Related Questions