【问题标题】:How do I access context and args in resolver at the same time?如何同时访问解析器中的上下文和参数?
【发布时间】:2021-04-06 14:03:24
【问题描述】:

这是我的 nestJS 应用程序中的解析器示例(使用 graphQL):

在第一个查询中我访问上下文,在第二个查询中我通过装饰器访问 args。

import { Args, Query, Resolver } from '@nestjs/graphql'

@Resolver('List')
export class ListResolvers {
  constructor(private readonly listService: ListService) {}

  @Query(() => [Data])
  async getList(obj, args, context) {
    const token = context.token
    return this.listService.getList(token)
  }

  @Query(() => [Data])
  async getList(
    @Args('param') param: GetListParam
  ): Promise<Array<Data>> {
    return this.listService.getList(param)
  }
}

但我确实需要同时通过:paramtoken

return this.listService.searchList(param, token)

如何在第二个查询(使用@Args 的查询)中访问上下文?

【问题讨论】:

    标签: javascript nestjs


    【解决方案1】:

    您可以使用此方法访问请求标头。 首先在 app.module.ts

    中的 graphqlModule 导入中添加 context
    imports: [
    GraphQLModule.forRoot({ ..., context: ({req}) => ({req})})
    ]
    

    然后像这样在 graphql 查询中使用上下文

     @Query(() => [Data])
      async getList(
        @Args('param') param: GetListParam,
        @Context('req') req
      ): Promise<Array<Data>> {
        const token = req.headers.authorization;
        return this.listService.getList(param)
      }
    

    【讨论】:

    • 我从哪里得到@Contextreq?我已经在 app.modules.ts 中设置了context: ({ req }) =&gt; ({ token: req.headers.authorization })
    • @user3142695 你是什么意思?只需从@nestjs/graphql 导入上下文,然后在解析器中使用它,就像@Context('token') token 一样。这应该工作
    猜你喜欢
    • 2020-09-12
    • 2023-03-22
    • 2019-09-21
    • 2019-11-25
    • 2015-06-02
    • 2021-01-17
    • 2021-06-22
    • 2018-07-15
    • 2021-10-16
    相关资源
    最近更新 更多