Skip to content

How to best handle long-running servers that reuse connections across requests? #3499

Answered by maou-shonen
psteinroe asked this question in Q&A
Discussion options

You must be logged in to vote

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)

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by psteinroe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants