Submit an array of objects as a query variable in graphQL

蓝咒 提交于 2019-12-11 05:21:49

问题


How can I structure the query parameters a graphQL mutation when one of the fields is an array of objects? When I hard-code the mutation this is valid and works:

mutation{
  submitResponse(user: "1234", responses: [{ answerId: "wmtBCWtkSeDs5meBe", selected: false}, { answerId: "wmtBCWtkSeDs5meBz", selected: true}]) {
    id
  }
}

I can't for the life of me figure out how to pass in query parameters for the responses array of objects. How can I define the type of each field in the object. This is what it would like for the user id and that works fine but I can't figure out the responses piece of it.

mutation submitResponse($user: ID!){
  submitResponse(user: $user, responses: [{ answerId: "wmtBCWtkSeDs5meBe", selected: false}, { answerId: "wmtBCWtkSeDs5meBz", selected: true}]) {
    id
  }
}

Thanks!


回答1:


I know that the question is old, but maybe someone else needs simple solution.

  1. Set type of responses as String!

    mutation submitResponse($user: ID!, $responses: String!){
      submitResponse(user: $user, responses: $responses) {
        id
      }
    }
    
  2. Then:

    yourData = [{ answerId: "wmtBCWtkSeDs5meBe", selected: false}, { answerId: "wmtBCWtkSeDs5meBz", selected: true}]
    responses = JSON.stringify(yourData)
    
  3. In my case in BackEnd I use Python, so receive responses in BackEnd and then simply convert JSON (string) to Python's dict, something like:

    import json
    responses = json.loads(input.get('responses'))
    


来源:https://stackoverflow.com/questions/45910230/submit-an-array-of-objects-as-a-query-variable-in-graphql

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