h3 icon indicating copy to clipboard operation
h3 copied to clipboard

unctx / Async Local Storage Support

Open rijkvanzanten opened this issue 1 year ago • 2 comments

Describe the feature

Hi there!

I'm hoping to use unctx to set a context for the current route event handler stack in h3, ideally as a middleware call:

app.get('/', useRouteContext, routeHandler);

that way, the route handler could use composable utilities that rely on the current context, like a useDatabase(). Do you have a recommended / example usage of this pattern? Seeing that the context callback seems to be required for nested functions, you'd end up with something like:

import { createContext } from "unctx";
import { createApp, createRouter, eventHandler } from 'h3';
import { routeHandler } from './routes/example.js';

const ctx = createContext();

const app = createApp();
const router = createRouter();

router.get('/', eventHandler((event) => {
  ctx.call({}, () => {
    routeHandler(event);
  });
});

Do you have any thoughts/feelings/concerns around this concept/pattern? More than happy to help document / continue solidifying this idea, but could really use a gut-check if this could work of if it's an insane idea 🙂

Additional information

  • [X] Would you be willing to help implement this feature?

rijkvanzanten avatar May 15 '23 21:05 rijkvanzanten