【问题标题】:Get parent object in child resolver AWS AppSync在子解析器 AWS AppSync 中获取父对象
【发布时间】:2021-12-03 20:40:09
【问题描述】:

我有一个这样的 graphQL 架构:

type Post {
    id: String!
    title: String!
    content: String!
    user: User!
}

type Query {
    allPosts: [Post!]
    singlePost(id: String!): Post!
}

type User {
    name: String!
    posts: [Post!]
}

发电机数据源处理查询。在下面的查询中,将使用不同的解析器来处理用户,因为它依赖于不同的 GSI。

query MyQuery {
  allPosts {
    content
    title
    user{
      name
    }
  }
}

allPosts 解析器如下所示:

{
    "version" : "2017-02-28",
    "operation" : "Query",
    "query" : {
        "expression" : "#t = :sk",
        "expressionNames" : {
          "#t": "type"
        },
        "expressionValues" : {
            ":sk": $util.dynamodb.toDynamoDBJson("post")
        }
    },
    "index" : "GSI",
    "select" : "ALL_ATTRIBUTES"
}

Post 类型中user 的解析器是:

{
    "version" : "2017-02-28",
    "operation" : "Query",
    "query" : {
        "expression" : "PK = :pk AND SK = :sk",
        
        "expressionValues" : {
            ":pk": "NEED TO ACCESS THE Partition KEY FROM ALL_POSTS",
            ":sk": $util.dynamodb.toDynamoDBJson("profile")
        }
    },
    "select" : "ALL_ATTRIBUTES"
}

我需要在每次迭代中从 post 对象访问分区键以获取特定 id 的用户,就像此代码中的作者解析器 (https://github.com/benawad/graphql-n-plus-one-example/blob/master/src/index.js):

const resolvers = {
  Book: {
    author: async parent => {
      const author = await knex("users")
        .select()
        .where("id", parent.authorId)
        .first();

      return author;
    }
  },
  Query: {
    books: async () => {
      const books = await knex("books")
        .select()
        .limit(10);
      return books;
    }
  }
};

【问题讨论】:

    标签: amazon-web-services graphql aws-appsync resolver vtl


    【解决方案1】:

    我终于找到了答案,需要的对象存储在$ctx.source中。我所要做的就是将user 解析器更改为此(假设结果对象中有PK):

    {
        "version" : "2017-02-28",
        "operation" : "Query",
        "query" : {
            "expression" : "PK = :pk AND SK = :sk",
            
            "expressionValues" : {
                ":pk": $util.dynamodb.toDynamoDBJson($ctx.source.PK),
                ":sk": $util.dynamodb.toDynamoDBJson("profile")
            }
        },
        "select" : "ALL_ATTRIBUTES"
    }
    

    $context.source 引用正在解析的当前字段的父对象。在此示例中,$ctx.source.PK 指的是单个 Post 对象,然后将其用于查询表达式。 ($context 和 $ctx 相同)。它的工作原理与apollo-server 框架中的parent 参数完全相同。

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 2019-02-04
      • 2018-10-11
      • 2021-04-21
      • 2020-09-07
      • 2019-04-16
      • 2019-02-03
      • 2019-11-25
      • 2019-08-10
      相关资源
      最近更新 更多