Last active
April 12, 2024 04:56
-
-
Save yusukebe/bfb695e4c73a4683ffb8257c46c6ff6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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