amplify-category-api icon indicating copy to clipboard operation
amplify-category-api copied to clipboard

How to perform batch Create/Add mutation for a many-to-many relation in amplify app-sync?

Open socialyadept opened this issue 2 years ago • 1 comments

I just finished to test the Many-To-Many Connections example and It worked for me. However, I still can't figure it out how to use only one mutation (and if it's even possible) to achieve the same result as the one given in the documentation. For example:

mutation CreateLinks {
    p1u1: createPostEditor(input: { id: "P1U1", postID: "P1", editorID: "U1" }) {
        id
    }   
    p1u2: createPostEditor(input: { id: "P1U2", postID: "P1", editorID: "U2" }) {
        id
    }
}

So far I was able to handle this with promise, but I'm not sure if this is the best approach (because it involves to execute as much mutations as there are users):

        const users = [{id: "U1", username: "user1"}, {id: "U2", username: "user2"}];
        const post = { id: "P1", title: "Post 1" };
        /*
        After creating two users and a post using the appropriate mutations
        Using the CreatePost join below to make user1 and user2 editor on Post 1
        */
        function graphqlCreatePostEditor(editorID) {
            return new Promise((resolve, reject) => {
              resolve(
                API.graphql(graphqlOperation(createPostEditor, {
                  input: {
                      postID: post.id,
                      editorID
                    }
                }))
              )
            })
          }
  
        let promises = users.map(user=> {
            return graphqlCreatePostEditor(user.id)
            .then(e => {
                console.log(e)
            return e;
            })
        });

        Promise.all(promises)
            .then(results => {
                console.log(results)
            })
            .catch(e => {
                console.error(e);
            })

Originally posted by @devnantes44 in https://github.com/aws-amplify/amplify-cli/issues/91#issuecomment-553972429

Anyone having a solution to this? I just want to create a mutation that can first create the post and add all the editors let's say they come from an array directly into the join table of PostEditor table. Any clue?

socialyadept avatar Mar 12 '23 13:03 socialyadept