Skip to content

Instantly share code, notes, and snippets.

@yusukebe
Last active April 12, 2024 04:56
Show Gist options
  • Save yusukebe/bfb695e4c73a4683ffb8257c46c6ff6c to your computer and use it in GitHub Desktop.
Save yusukebe/bfb695e4c73a4683ffb8257c46c6ff6c to your computer and use it in GitHub Desktop.
import { AsyncLocalStorage } from 'node:async_hooks'
const useStorage = <E extends unknown>() => {
const localStorage = new AsyncLocalStorage()
return {
store: <T>(env: E, callback: () => T): T => {
return localStorage.run(env, callback)
},
get: (key: keyof E) => {
const store = localStorage.getStore() as E
return store[key]
}
}
}
type Env = {
MY_KV: KVNamespace
}
const { store, get } = useStorage<Env>()
async function outSideOfHandler() {
console.log(await get('MY_KV').get('key'))
}
export default {
async fetch(req, env, ctx) {
return store(env, async () => {
env.MY_KV.put('key', 'foo')
await outSideOfHandler()
return new Response('Hi')
})
}
} satisfies ExportedHandler<Env>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment