Why would you need to store it? Why not just stream it back to the client once it has been modified?
Why would you need to store it? Why not just stream it back to the client once it has been modified?
global.js, containing a {}, which multiple scripts import and hook things onto, will this leak/bleed into multiple requests to my worker given Node's import caching, or will it be isolated to just the current request?foo=1, and I want to hook that onto a global object so other files can use it, rather than laboriously having to pass it around to all functions. But the next request may send QS foo=2. Sounds like I'll be OK based on what you say. (But presumably in a non-serverless/Worker environment this would be problematic?)
globalObject.localStorage wouldn't work? If so, using AsyncLocalStorage, am I right that it would look something like this, to store a global property for later reading downstream?run takes the object you want to store, and then a callbackrun requires the callbackmystore.run({foo: bar}) is insufficient to write to the storage? If so, what would any callback I passed actually "do", if all I want to do is write for later reading?runrun and return my Response thereasyncLocalStorage.getStore(); to access req, env, ctxrun()'s callback?fooApi.bar() (in controllers/foo.js) be able to access that stored value.controllers/foo:alsglobalThis.als = new AsyncLocalStorage would workglobalThis in the first place and bypass ALS?)global.js{}foo=1foo=2globalObject.localStorageimport { AsyncLocalStorage } from 'node:async_hooks';
const fooStore = new AsyncLocalStorage();
fooStore.run('bar'); //<-- running in some async middlewareimport { AsyncLocalStorage } from 'node:async_hooks';
const fooStore = new AsyncLocalStorage();
const fooVal = fooStore.getStore(); //"bar"runrunrunrunmystore.run({foo: bar})asyncLocalStorage.getStore();run()import fooApi from '../controllers/foo'
router.post('/foo/bar', async req => {
const resp = fooApi.bar(); //e.g. "hello world"
return resp;
})fooApi.bar()controllers/foo.jscontrollers/fooexport default {
bar: () => {
//how to access local storage value in here? I'm not in the middleware's storage.run() callback at this point...
}
};alsglobalThis.als = new AsyncLocalStorageglobalThisimport { AsyncLocalStorage } from "node:async_hooks";
const asyncLocalStorage = new AsyncLocalStorage();
async function doStuff() {
const { req, env, ctx } = asyncLocalStorage.getStore();
const obj = await env.KV.get("foo");
// ...
}
export default {
async fetch(req, env, ctx) {
return asyncLocalStorage.run({ req, env, ctx }, async () => {
await doStuff();
return new Response("Hello World!");
});
},
};export const als = new AsyncLocalStorage();
router.get("/", async () => {
return als.run("foo", async () => {
const resp = foo.bar();
return new Response(resp);
});
});import { als } from ".";
export default {
bar: () => {
return als.getStore();
},
};