How to PUT / UPDATE nested data with GraphQL?

2020-07-31 03:13发布

问题:

I'm attempting my first GraphQL backend using AWS AppSync. I'm simply trying to figure out how to use one-to-many associations. I expect to receive the many related objects as a list of children, and to be able to write some of these children when creating a new user.

type User {
    id: ID!
    name: String!
    records: [Records!]!
}
type Records {
    id: ID!
    userId: ID!
    title: String!
    ... etc ...
}

Using the AppSync interface, I click on Create Resources once to make a Records table and again to make a Users table, both in DynamoDB. This also automatically adds mutations, subscriptions, input types, and more types, to my schema, and creates resolvers for me.

What is the syntax for a mutation to create Record objects associated with my User objects? How can I PUT the Record data when I create the User?

If needed I can include more of the schema that AppSync is autogenerating.

回答1:

Since you are using two DynamoDB tables (Users and Records), you will need to make two DynamoDB calls during the CreateUser mutation. One way to make two DynamoDB calls in a single mutation is to utilize DynamoDB's BatchPutItem operation.

To utilize BatchPutItem, you will need to modify the resolver which is attached to your CreateUser mutation. The resolver is responsible for taking your graphQL request, converting it into a DynamoDB operation, and then converting the results of the DynamoDB operation into a graphQL response. The resolvers have two components: a request mapping template, and a response mapping template.

The request mapping template will be responsible for taking mutation arguments and converting them into a DynamoDB BatchPutItem request.

The resolver's response mapping template will be responsible for converting the result of the DynamoDB BatchPutItem operation into your mutation's return type/structure.

Here is a tutorial on how to utilize multi-table BatchPutItem in a resolver: https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-batch.html

Here is a programming guide for using the Template language required for the resolvers: https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-programming-guide.html