GraphQL - How to chain queries and mutations? [duplicate]

こ雲淡風輕ζ 提交于 2019-12-07 05:34:10

问题


In my graphQL schema, I have a relationship between two objects. Say Humans and Cats.

Humans have many Cats and Cats have one human.

If I want to create a new Cat belonging to a human, I need to query for the human by ID and then I need to use that ID to do a mutation to create the cat.

How can I chain these together? It seems simple but can't find an appropriate example. It is also very likely that I'm thinking about this in the wrong way.


回答1:


I don't think it makes sense to chain them. If you want to create a new cat you need a list where you select the humans you want to add the cat to. So you already have to query for the humans, before you send the mutation.

The mutation for the cat would contain the selected human ids, the process could look like this:

  1. query for humans

const getAllHumansQuery = gql`
query getAllHumans {
   getAllHumans {
      id
      name
   }
}
`;
  1. Build form with selection of humans on the client

  2. Send create new cat mutation

// server
`
input CatInput {
  name: String!
  humanIds: [ID!]
}

createCat(newCat: CatInput!) : String
`


// client

const createCatMutation = gql `
  mutation createCat($newCat: CatInput!) {
    createCat(newCat: $newCat) {
      name
    }
  }
`;


来源:https://stackoverflow.com/questions/43624620/graphql-how-to-chain-queries-and-mutations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!