How to make a mutation query for inserting a list of (Array) fields in GraphQL

后端 未结 2 618
夕颜
夕颜 2021-02-01 19:05

recently I started working on GraphQL, I am able to insert data in flat schema without any problem but when it comes to an Array of data I am getting an error like



        
相关标签:
2条回答
  • 2021-02-01 19:21

    Your issue is that when you define mutations, all types must be input types, hence the error you get "Must be input type". So in here (from your mutation):

    media:{
      type:new GraphQLList(mediaType),
      description:'List of media',   
    },
    location:{
      type:new GraphQLList(locationType),
      description:'List of media',   
    },
    

    GraphQLList, mediaType and locationType must be input types.

    GraphQLList is already an input type (see here https://github.com/graphql/graphql-js/blob/master/src/type/definition.js#L74-L82 to see the list of GraphQL types considered as input types).

    However your types mediaType and locationType are of GraphQLObjectType type, which is not an input type but if you look at the list of input types again: https://github.com/graphql/graphql-js/blob/master/src/type/definition.js#L74-L82, you'll find GraphQLInputObjectType which is an object input type, so, what you need to do is to replace mediaType and locationType by their "input" version.

    What I suggest to do is to create mediaInputType and locationInputType which would have the same field structure as mediaType and locationType but created with new GraphQLInputObjectType({... instead of new GraphQLObjectType({... and use them in your mutation.

    I ran into the same issue and I solved it like that, feel free to comment if you have any question.

    0 讨论(0)
  • 2021-02-01 19:34

    I ran into the same problem - I did not know how to specify array of objects in the input definition. So for those who wants to see a "text" schema solution:

    type Book {
      title: String!
    }
    

    to have an array of Books in your input type

    input AuthorInput {
      name: String!
      age: Int!
    }
    

    you can not just add books: [Book!] inside the input statement, you will need deliberately create input type containing needed fields (duplicate if you like):

    input BookInput {
      title: String!
    }
    

    and then you can:

    input AuthorInput {
      name: String!
      age: Int!
      books: [BookInput!]
    }
    
    0 讨论(0)
提交回复
热议问题