How to best handle long-running servers that reuse connections across requests? #3499
-
Hey, I am migrating a hono service from cf workers to a node service and need to replace something that was a simple http request before with multiple Redis connections. I am wondering what's the cleanest and most idiomatic way is. My current approach is simply declaring a variable outside of the handler and on first request initialise it. Its then passed to the context as usual. let fnClient: FunctionsClient;
const app = new Hono<Env>();
app.use((c, next) => {
if (!fnClient) {
fnClient = new FunctionsClient({
host: env("REDIS_HOST"),
port: env("REDIS_PORT"),
});
}
c.set("services", {
logger,
fnClient,
});
return next();
}); This feels a big sluggish for me. Is there a better way? |
Beta Was this translation helpful? Give feedback.
Answered by
maou-shonen
Oct 13, 2024
Replies: 1 comment
-
I guess you're looking for something like this. hono.js middleware can also be dependency injection! import { Hono } from "hono"
import { createMiddleware } from "hono/factory"
import { Redis } from "ioredis"
const redisUrls = {
default: "redis://127.0.0.1:6379",
test1: "redis://127.0.0.1:16379",
test2: "redis://127.0.0.1:26380",
}
type RedisKey = keyof typeof redisUrls
const clients = new Map<RedisKey, Redis>()
const useRedis = <ContextKey extends string = "redis">(
redisKey: RedisKey,
contextKey?: ContextKey,
) => {
type Env = {
Variables: {
[key in ContextKey]: Redis
}
}
contextKey ??= "redis" as ContextKey
return createMiddleware<Env>(async (c, next) => {
if (!clients.has(redisKey)) {
const redisUrl = redisUrls[redisKey]
clients.set(redisKey, new Redis(redisUrl))
}
const redis = clients.get(redisKey)!
c.set(contextKey, redis)
await next()
})
}
const app = new Hono()
.get("/", useRedis("default"), async (c) => {
const redis = c.get("redis") // redis://127.0.0.1:6379
return c.text("")
})
.get("/foo", useRedis("test1"), async (c) => {
const redis = c.get("redis") // redis://127.0.0.1:16379
return c.text("")
})
.get(
"/multi",
useRedis("test1", "redis1"),
useRedis("test2", "redis2"),
async (c) => {
const redis1 = c.get("redis1") // redis://127.0.0.1:16380
const redis2 = c.get("redis2") // redis://127.0.0.1:26380
return c.text("")
},
) |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
psteinroe
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I guess you're looking for something like this.
hono.js middleware can also be dependency injection!