Skip to content

Wrapping operations / messages with asyncLocalStorage for requestContext #658

@dennemark

Description

@dennemark

Story

As a server I want to use AsyncLocalStorage to allow setting variables per subscription i.e. via @fastify/request-context.

In my graphql routes i use @fastify/request-context. I would like to wrap the iterator of operationResult into asyncLocalStorage or maybe more convenient: onMessage. Then i could set requestContext i.e. on onSubscribe.

The following looks unnecessarily complicated but it seems to work:

import { asyncLocalStorage, requestContext } from '@fastify/request-context'

onOperation: (ctx, id, payload, execArgs, operationResult) => {
        const currentTenant = undefined
        const wrappedOperationResult = {
          async next() {
            return await asyncLocalStorage.run(new Map(), async () => {
                requestContext.set('group', ctx?.connectionParams?.['group'])
              const result = await operationResult.next()
              return result
            })
          },
          [Symbol.asyncIterator]() {
            return this
          },
          return(value) {
            return operationResult.return(value)
          },
          throw(error) {
            return operationResult.throw(error)
          },
        }
        return wrappedOperationResult
      },
``

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions