N
Nuxt10mo ago
Flo

Composable for accessing event scoped data?

Given following server middleware:
export default eventHandler(async (event) => {
// No protection for auth routes
if (event.path.startsWith("/api/auth")) {
return;
}

const session: Session | null = await getServerSession(event);

if (session) {
// To be used throughout the app
event.context.currentUser = {
name: session.user?.name,
email: session.user?.email,
role: useRoles().getHighestRole(session.roles!),
uid: session.uid,
key: session.key,
} as currentUser;
}
...
return
}
export default eventHandler(async (event) => {
// No protection for auth routes
if (event.path.startsWith("/api/auth")) {
return;
}

const session: Session | null = await getServerSession(event);

if (session) {
// To be used throughout the app
event.context.currentUser = {
name: session.user?.name,
email: session.user?.email,
role: useRoles().getHighestRole(session.roles!),
uid: session.uid,
key: session.key,
} as currentUser;
}
...
return
}
and an api handler calling a composable useSomeCustomComposable(), is there a way to access the currentUser-object in that composable without passing it through function arguments? Above implementation was an experiment. Happy to change that. Background: That custom composable is used in many routes. For the sake of code dedup, I'd prefer to not extend all calls with something that never changes. I'm propably just blind and it's an easy thing to do, but neither my brain, nor chatgpt were really helpful with that so far.
4 Replies
rc
rc10mo ago
you can use nitro's experimental async context feature to handle this https://nitro.unjs.io/guide/utils#async-context-experimental
Nitro
Server Utils · Nitro
Create web servers with everything you need and deploy them wherever you prefer.
rc
rc10mo ago
else you could try using async local storage from node https://docs.adonisjs.com/guides/async-local-storage
rc
rc10mo ago
I haven't seen anyone use it in production yet. I believe it is stable, but I would advise doing some googling to make sure.
Flo
FloOP10mo ago
amazing!
Want results from more Discord servers?
Add your server