Amazon Dynomo DB:由于AppSync_assume_role和键入不匹配错误,batchputitIte



我正在使用AWS Amplify构建一个React应用程序。我使用Cognito用户池进行身份验证和GraphQl AppSync后端的后端。

我正在尝试编写一个自定义解析器以进行批处理突变。这是我使用的模式:

type Todo @model @auth(rules: [{ allow: owner }]) {
  id: ID!
  title: String!
  description: String
  completed: Boolean
}
input CreateTodoInput {
  id: ID
  title: String!
  description: String
  completed: Boolean
}
type Mutation {
  batchAddTodos(todos: [CreateTodoInput]): [Todo]
}

此模式可以使用Cognito用户池对GraphQl API进行身份验证。

为了使此自定义突变起作用,需要添加自定义解析器。我更改了amplify/api/<your-api-name>/stacks/CustomResources.json以包含以下资源:

// Left everything as it was
 "Resources": {
    "EmptyResource": {
      "Type": "Custom::EmptyResource",
      "Condition": "AlwaysFalse"
    },
    "BatchAddTodosResolver": {
      "Type": "AWS::AppSync::Resolver",
      "Properties": {
        "ApiId": {
          "Ref": "AppSyncApiId"
        },
        "DataSourceName": "TodoTable",
        "TypeName": "Mutation",
        "FieldName": "batchAddTodos",
        "RequestMappingTemplateS3Location": {
          "Fn::Sub": [
            "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.batchAddTodos.req.vtl",
            {
              "S3DeploymentBucket": {
                "Ref": "S3DeploymentBucket"
              },
              "S3DeploymentRootKey": {
                "Ref": "S3DeploymentRootKey"
              }
            }
          ]
        },
        "ResponseMappingTemplateS3Location": {
          "Fn::Sub": [
            "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.batchAddTodos.res.vtl",
            {
              "S3DeploymentBucket": {
                "Ref": "S3DeploymentBucket"
              },
              "S3DeploymentRootKey": {
                "Ref": "S3DeploymentRootKey"
              }
            }
          ]
        }
      }
    }
  },
// ... more code that I didn't touch

对于自定义请求解析器,我编写了以下模板:

#foreach($item in ${ctx.args.todos})
    ## [Start] Owner Authorization Checks **
    #set( $isOwnerAuthorized = false )
    ## Authorization rule: { allow: "owner", ownerField: "owner", identityField: "cognito:username" } **
    #set( $allowedOwners0 = $util.defaultIfNull($item.owner, null) )
    #set( $identityValue = $util.defaultIfNull($ctx.identity.claims.get("username"),
    $util.defaultIfNull($ctx.identity.claims.get("cognito:username"), "___xamznone____")) )
    #if( $util.isList($allowedOwners0) )
        #foreach( $allowedOwner in $allowedOwners0 )
            #if( $allowedOwner == $identityValue )
                #set( $isOwnerAuthorized = true )
            #end
        #end
    #end
    #if( $util.isString($allowedOwners0) )
        #if( $allowedOwners0 == $identityValue )
            #set( $isOwnerAuthorized = true )
        #end
    #end
    #if( $util.isNull($allowedOwners0) && (! $item.containsKey("owner")) )
        $util.qr($item.put("owner", $identityValue))
        #set( $isOwnerAuthorized = true )
    #end
    ## [End] Owner Authorization Checks **
    ## [Start] Throw if unauthorized **
    #if( !($isStaticGroupAuthorized == true || $isDynamicGroupAuthorized == true || $isOwnerAuthorized
        == true) )
        $util.unauthorized()
    #end
    ## [End] Throw if unauthorized **
#end
#set($todosdata = [])
#foreach($item in ${ctx.args.todos})
    $util.qr($item.put("createdAt", $util.time.nowISO8601()))
    $util.qr($item.put("updatedAt", $util.time.nowISO8601()))
    $util.qr($item.put("__typename", "Todo"))
    $util.qr($item.put("id", $util.defaultIfNullOrBlank($item.id, $util.autoId())))
    $util.qr($todosdata.add($util.dynamodb.toMapValues($item)))
#end
{
  "version": "2018-05-29",
  "operation": "BatchPutItem",
  "tables": {
      "TodoTable": $utils.toJson($todosdata)
  }
}

使用第一个循环,我试图验证用户可以访问他创建的毒品。在第二个循环的情况下,我添加了由放大CLI生成的解析器添加的数据。这包括__typename,时间戳和id

之后,我提出了创建资源的请求。我遵循本教程的代码。请注意,我必须将版本更新为"2018-05-29"。放大CLI生成的代码通常具有"2017-02-28"的版本(我不知道这是否重要)。

我还为响应解析器编写了以下映射:

#if ($ctx.error)
    $util.appendError($ctx.error.message, $ctx.error.type, null, $ctx.result.data.unprocessedKeys)
#end
$util.toJson($ctx.result.data)

这基本上告诉AppSync返回数据和所有未经处理项目的错误。

我首先尝试使用React提出请求:

import API, { graphqlOperation } from '@aws-amplify/api';
// ... later
async function handleClick() {
  const todoFixtures = [
    { id: 1, title: 'Get groceries', description: '', completed: false },
    { id: 2, title: 'Go to the gym', description: 'Leg Day', completed: true }
  ];
  try {
    const input = { todos: prepareTodos(todoFixtures) };
    const res = await API.graphql(graphqlOperation(batchAddTodos, input));
    console.log(res);
  } catch (err) {
    console.log('error ', err);
  }
}

prepareTodos只是摆脱了id字段,并将空字段设置为null(以避免DynamoDB对我大喊大叫)。代码在底部,因为它无关紧要。

由于失败了,我尝试通过Appsync控制台进行突变:

mutation add {
  batchAddTodos(todos: [
    {title: "Hello", description: "Test", completed: false}
  ]) {
    id title
  }
}

,但两次尝试都丢下以下错误:

{
  "data": {
    "batchAddTodos": null
  },
  "errors": [
    {
      "path": [
        "batchAddTodos"
      ],
      "data": null,
      "errorType": "DynamoDB:AmazonDynamoDBException",
      "errorInfo": null,
      "locations": [
        {
          "line": 32,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "User: arn:aws:sts::655817346595:assumed-role/Todo-role-naona7ytt5drxazwmtp7a2uccy-batch/APPSYNC_ASSUME_ROLE is not authorized to perform: dynamodb:BatchWriteItem on resource: arn:aws:dynamodb:eu-central-1:655817346595:table/TodoTable (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: AccessDeniedException; Request ID: EP48SJPVMB9G9M69HPR0BO8SKJVV4KQNSO5AEMVJF66Q9ASUAAJG)"
    },
    {
      "path": [
        "batchAddTodos"
      ],
      "locations": null,
      "message": "Can't resolve value (/batchAddTodos) : type mismatch error, expected type LIST"
    }
  ]
}

这使我相信反应代码是"正确的"或至少与AppSync代码同样错误的。但是我怀疑该错误在解析器模板映射中的某个地方。我只是找不到。这里出了什么问题?

也许生成的假设 - 词不支持"2018-05-19"版本?这是角色默认生成角色的代码(我没有写):

 "AssumeRolePolicyDocument": {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "appsync.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
},
"Policies": [
    {
        "PolicyName": "DynamoDBAccess",
        "PolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "dynamodb:BatchGetItem",
                        "dynamodb:BatchWriteItem",
                        "dynamodb:PutItem",
                        "dynamodb:DeleteItem",
                        "dynamodb:GetItem",
                        "dynamodb:Scan",
                        "dynamodb:Query",
                        "dynamodb:UpdateItem"
                    ],
                    "Resource": [
                        {
                            "Fn::Sub": [
                                "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tablename}",
                                {
                                    "tablename": {
                                        "Fn::If": [
                                            "HasEnvironmentParameter",
                                            {
                                                "Fn::Join": [
                                                    "-",
                                                    [
                                                        "Todo",
                                                        {
                                                            "Ref": "GetAttGraphQLAPIApiId"
                                                        },
                                                        {
                                                            "Ref": "env"
                                                        }
                                                    ]
                                                ]
                                            },
                                            {
                                                "Fn::Join": [
                                                    "-",
                                                    [
                                                        "Todo",
                                                        {
                                                            "Ref": "GetAttGraphQLAPIApiId"
                                                        }
                                                    ]
                                                ]
                                            }
                                        ]
                                    }
                                }
                            ]
                        },
                        {
                            "Fn::Sub": [
                                "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tablename}/*",
                                {
                                    "tablename": {
                                        "Fn::If": [
                                            "HasEnvironmentParameter",
                                            {
                                                "Fn::Join": [
                                                    "-",
                                                    [
                                                        "Todo",
                                                        {
                                                            "Ref": "GetAttGraphQLAPIApiId"
                                                        },
                                                        {
                                                            "Ref": "env"
                                                        }
                                                    ]
                                                ]
                                            },
                                            {
                                                "Fn::Join": [
                                                    "-",
                                                    [
                                                        "Todo",
                                                        {
                                                            "Ref": "GetAttGraphQLAPIApiId"
                                                        }
                                                    ]
                                                ]
                                            }
                                        ]
                                    }
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    }
]

prepareTodos

const map = f => arr => arr.map(f);
const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
const dissoc = prop => ({ [prop]: _, ...obj }) => obj;
const mapObj = f => obj =>
  Object.keys(obj).reduce((acc, key) => ({ ...acc, [key]: f(obj[key]) }), {});
const replaceEmptyStringWithNull = x => (x === '' ? null : x);
const prepareTodos = map(
  pipe(
    dissoc('id'),
    mapObj(replaceEmptyStringWithNull)
  )
);

编辑:我设法求解了Typemismatch。在响应中,我必须返回: $util.toJson($ctx.result.data.TodoTable)

响应模板中的 $util.toJson($ctx.result.data.TodoTable),以及将 TodoTable更改为实际表名称(您可以在控制台中的dynamodb下查找它,看起来像该 Todo-dqeronnsgvd2pf3facjmlgtsjk-master)解决了错误。<<<<<<<<<<<<<<<<<<<<<<<<<<<<

这也是我在偶然发现这个问题时写过的逐步教程。

相关内容

  • 没有找到相关文章