这是我的 NestJS 应用程序中的解析器示例(使用 graphQL):
在第一个查询中,我正在访问上下文,在第二个查询中,我通过装饰器访问参数。
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)
}
}
Run Code Online (Sandbox Code Playgroud)
但我确实需要通过:param和token:
return this.listService.searchList(param, token)
Run Code Online (Sandbox Code Playgroud)
如何访问第二个查询(使用 的查询@Args)中的上下文?
您可以使用此方法访问请求标头。首先在app.module.ts中的 graphqlModule 导入中添加上下文
imports: [
GraphQLModule.forRoot({ ..., context: ({req}) => ({req})})
]
Run Code Online (Sandbox Code Playgroud)
然后在 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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3498 次 |
| 最近记录: |