0
votes

After adding a request scoped service to an existing codebase, many of the seeder functions calling services directly return undefined for request scoped services (as no HTTP request has actually been sent).

How can I "seed" a request instance so it's available and can be resolved as a dependency in the service?

1

1 Answers

1
votes

The following utility function will seed a request and return an ID for usage:

import { INestApplication } from '@nestjs/common'
import { ContextIdFactory } from '@nestjs/core'

/**
 * Seeds a request and returns the context ID
 * for referencing (e.g. for `NestApplication.resolve()`).
 *
 * Request scoped services rely on a HTTP request
 * to be made to be instantiated, and
 * seeders do not fire HTTP requests to
 * generate context.
 */
export const seedRequest = <T extends {}>(app: INestApplication, req: T) => {
  const contextId = ContextIdFactory.create()
  app.registerRequestByContextId(req, contextId)

  return {
    contextId,
  }
}

Use like so:

const app: INestApplication

// initialise app, etc...

const contextId = seedRequest(app, {
  req: {
    user: {
      id: 'abc123',
    },
  },
})

const someService = await app.resolve(SomeService, contextId)

// use someService...