How can I initialize some services with Context on startup? #4089
Unanswered
ShookLyngs
asked this question in
Q&A
Replies: 1 comment
-
|
I do this in middleware and set the services on the Variables interface: interface Variables {
// services
ai: AIService;
apns: APNs;
db: DrizzleD1Database;
slack: Slack;
// auth
session: ISession | null;
}
const app = new Hono<{ Bindings, Variables }>();
// services middleware
app.use(async (c, next) => {
c.set("ai", new AIService(c.env));
c.set("apns", new APNs(c.env));
c.set("db", drizzle(c.env.MY_DB));
c.set("slack", new Slack(c.env));
await next();
});
// some endpoint
app.get('/something, async (c) => {
return c.var.db //…
})Since Hono runs on stateless architecture, like Cloudflare workers, there is no onInit. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Say I have a service, that it can be initialized with the Context object.
By default, the service is only be initialized when requests come in:
Say Hono app is running in Node.js runtime, and the service should only be initialized once per app, I wonder if it is possible to initialize the service on Hono app startup, like this (note the Context object is required for the service initialization):
Beta Was this translation helpful? Give feedback.
All reactions