AWS Appsync解析器:如何创建解析器以更新列表映射(DynaMoDB)中的项目

时间:2019-05-29 02:42:06

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

我正在一个表中创建多个对象,我在这里有一个名为“ User”的示例DynamoDB表,其中包含字段(名字,姓氏,电子邮件,公司),有人可以知道如何创建解析器以在历史记录中添加新项目?谢谢。

{
  "id": "d7913a57-f458-4b81-8d6e-10f81e2b1dc2",
  "firstName": "John",
  "lastName": "Doe",
  "email": "johndoe@gmail.com",
  "companies" : [
      {
        "companyId": "6059be51-1e66-4f3a-9c8f-ced3bc89d562",
        "createdAt": 321321,
        "histories": [
          {
           "companyHistoryId": "dc9d1a57-fb82-4c25-a6cf-d27dfe114f8f",
           "content": "Company A was created.",
           "createdAt": 321321,
           "createdBy": "d7913a57-f458-4b81-8d6e-10f81e2b1dc2"
          }
        ],
     },
  ]
}

这是我用来添加新公司的解析器

{
    "version" : "2017-02-28",
    "operation" : "UpdateItem",
    "key" : {
        "id": { "S": "${context.arguments.id}" },
    },
    "update" : {
        "expression" : "SET companies = list_append(if_not_exists(companies, :emptyList), :newCompany)",
        "expressionValues" : {
            ":emptyList": { "L" : [] },
            ":newCompany" : { "L" : [
                { "M": {
                    "name": { "S" : "${context.arguments.name}" },
                    "createdAt": { "N" : "${context.arguments.createdAt}" },
                    "companyId": { "S": "$util.autoId()" },
                    "isActive": { "BOOL" : true },
                    "histories": { "L": [
                        { "M": {
                            "companyHistoryId": { "S": "$util.autoId()" },
                            "content" : { "S" : "${context.arguments.name} was created." },
                            "createdAt": { "N" : "${context.arguments.createdAt}" },
                            "createdBy": { "S": "${context.arguments.id}" }
                        }}
                    ] }
                }}
            ] },
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

{
  "version" : "2017-02-28",
  "operation" : "UpdateItem",
  "key" : {
      "id": { "S": "${context.arguments.id}" },
  },
  "update" : {
      "expression" : "SET companies[$ctx.args.index].histories = list_append(if_not_exists(companies[$ctx.args.index].histories, :emptyList), :history)",
      "expressionValues" : {
          ":emptyList": { "L" : [] },
          ":history" : { "L": [
              { "M": {
                  "companyHistoryId": { "S": "$util.autoId()" },
                  "content" : { "S" : "${context.arguments.name} was created." },
                  "createdAt": { "N" : "${context.arguments.createdAt}" },
                  "createdBy": { "S": "${context.arguments.id}" }
              }}
          ] }
      }
  }
}

请记住传递$ctx.args.index,它是companies项目的索引,其histories将被更新。