簡體   English   中英

如何在GraphQL和Nestjs執行上下文中訪問父查詢arguments

[英]How to access parent query arguments in GraphQL and Nestjs execution context

假設我們有一家書店和一個作者實體,為了向作者顯示他們的收入統計數據,我們想檢查經過身份驗證的用戶是否確實是作者本人。 所以我們有:

  @UseGuards(GqlAuthGuard)
  @ResolveField(() => [Eearning], { name: 'earnings' })
  async getEarnings(
    @Parent() author: Author,
    @GqlUser() user: User,
  ) {
    if (user.id !== author.id)
      throw new UnauthorizedException(
        'Each author can only view their own data',
      );
    // rest of the function implementation
  }

我們可以這樣查詢:

query {
  author(id: "2bd79-6d7f-76a332b06b") {
    earnings {
      sells
    }
  }
}

現在假設我們想要使用自定義 Guard 而不是 if 語句。 像下面這樣的東西:

@Injectable()
export class AutherGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const ctx = GqlExecutionContext.create(context);
    // const artistId = ?
  }
}

AutherGuard用於getEarnings處理程序時,如何訪問提供給author查詢的id參數?

不確定是如何記錄的,但是可以通過getRoot方法訪問父 object:

const gqlContext = GqlExecutionContext.create(context);
const root = gqlContext.getRoot();
const authorId = root.id;

事實上,我們有一個 helper function,我們可以這樣使用:

export function getArgs(context: ExecutionContext): any {
  if (context.getType<GqlContextType>() === "graphql") {
    const gqlContext = GqlExecutionContext.create(context);
    return { ...gqlContext.getArgs(), $parent: gqlContext.getRoot() };
  } else if (context.getType() === "http") {
    return context.switchToHttp().getRequest().params;
  }
}

...
const args = getArgs(context);
const authorId = _.get(args, "$parent.id");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM