Nestjs调用请求范围内的服务而无需请求

时间:2020-07-03 15:59:16

标签: nestjs

将请求范围的服务添加到现有代码库后,许多调用服务的种子函数会直接为请求范围的服务返回undefined(因为实际上没有发送HTTP请求)。

如何“种子”请求实例,使其可用并可以作为服务中的依赖项进行解析?

1 个答案:

答案 0 :(得分:0)

以下实用程序函数将播种请求并返回ID以供使用:

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,
  }
}

使用方式如下:

const app: INestApplication

// initialise app, etc...

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

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

// use someService...