Re-Post of https://github.com/orgs/honojs/discussions/1889:
I have a Hono (https://hono.dev/) web application with a ttlCache
variable in the context c
:
import { serve } from "@hono/node-server"
import { Hono } from "hono"
import TTLCache from "@isaacs/ttlcache"
// How/where can I initialize ttlCache?
const app = new Hono<{ Variables: { ttlCache: TTLCache<string, string> } }>()
// In the route handlers, I will use ttlCache.
app.get("/", (c) => c.text("The TTLCache is " + c.var.ttlCache))
serve(app, (info) => {
console.log(`Listening on http://localhost:${info.port}`)
})
Not surprising, when I run the app and load http://localhost:3000, I see the response "The TTLCache is undefined".
How can I initialize the ttlCache variable on startup, e.g. to the following value?
new TTLCache({ max: 10000, ttl: 1000 })
(The above is a minimal demo for the problem. In reality I will use ttlCache to store objects...)
You can initialize it as a global variable, then set the value to your
ttlCache
variable in the middleware. something like this -and then for accessing the value
You can refer to the docs for more detail - https://hono.dev/api/context#set-get