HowToGraphQL - 第 6 章身份验证 - 为什么调用 postedBy()?

HowToGraphQL - Chapter 6 Authentication - Why is postedBy() invoked?

我希望在问这个问题时能弄清楚,因为 GraphQL 是一个相当晦涩的概念,而且网上没有那么多答案。

在教程 (https://www.howtographql.com/graphql-js/6-authentication/) 中靠近页面中间的#Resolving relations 部分有这段代码:

function postedBy(parent, args, context) {
  return context.prisma.link.findUnique({ where: { id: parent.id } }).postedBy()
}

为什么最后调用postedBy()?

超级困惑。

这部分 与 auth 没有严格的关系 [原因] ... 创建 post 突变将在没有它的情况下起作用。但是:

  • post 突变创建一个 [Link] 条目与关系(到 User in prisma schema 意思是 docs );
  • postedBy 是一个虚拟字段 - 'Relation fields define connections between models at the Prisma level and do not exist in the database. ';
  • post 突变 return 是一个 Post 类型 - 然后 'asked' return 对象可以包含 postedBy 字段(及其 User object/type 子字段[-s]);
  • 当查询 postedBy 字段时(作为突变结果树的一部分),它(相关 User object/type - graphql 上下文)必须使用 function postedBy(parent, args, context) 解析;

在解析器主体中,我们 using/working 使用“Prisma 客户端”- ORM 库,然后:

context.prisma.link.findUnique({ where: { id: parent.id } }).postedBy()
  • context.prisma is/gives 从 graphql 服务器上下文访问客户端;
  • context.prisma.link is/gives 访问 links API:

From docs: Models:

  • Represent the entities of your application domain;
  • Map to the tables in your database
  • Form the foundation of the queries available in the generated Prisma Client API
  • context.prisma.link.findUnique({ where: { id: parent.id } }) - 查询数据库 link 实体 - returns a Link 'instance' (prisma context);
  • context.prisma.link.findUnique({ where: { id: parent.id } }).postedBy() - 仍然是 prisma 客户端 API 上下文(不是 graphql - 解析器),不是 'calling itself';

查看文档:Prisma client fluent api

  • prisma 的 .postedBy() 连接到 User (prisma) 'instance',returned as/resolved 到 User (graphql) object/type(id 从 DB table 读取);

  • postedBy { id } 请求(在查询中)可以得到满足...但是 sendBy User 部分 post 突变结果(Link.postedBy) 可以要求包含 links(和子字段)- function links(parent, args, context) { 用于解决 relation/connection;

  • 每个 returned links 都可以查询 postedBy 个用户字段 ...

...这是一个 graph/tree,现在完全可以解析(节点、数据库条目和关系、虚拟)