Search code examples
graphqlgraphql-java

GraphQL Mutation not working with RuntimeWiring.newRuntimeWiring()


I have defined a simple schema in GraphQL Java to add Book and to fetch the [Book]. My Schema goes like:

schema {
 query: Query
 mutation : Mutation
}

type Query {
 allBooks: [Book]
 book(id: String): Book
}

type Book {
  isn: String
  title: String
  publisher: String
  author: String
  publishedDate: String
}

input BookType {
  isn: String
  title: String
  publisher: String
  author: String
  publishedDate: String
}

type Mutation {
  newBook(
      isn: String!,
      title: String!,
      publisher: String!,
      authors:String!,
      publishedDate: String!
  ): Book
}

I have create the runtime wiring like this:

RuntimeWiring.newRuntimeWiring()
  .type("Query", typeWiring ->
    typeWiring.dataFetcher("allBooks", allBooksDataFetcher))
  .type("Mutation", typeWiring ->
    typeWiring.dataFetcher("newBook", addBooksDataFetcher))
  .build();

The allBooks query is working fine but the newBook mutation is not working and gives following error:

"errors": [
  {
    "validationErrorType": "FieldUndefined",
    "message": "Validation error of type FieldUndefined: Field oneBook is undefined",
    "locations": [
      {
        "line": 3,
        "column": 3
      }
    ],
    "errorType": "ValidationError"
  }
],
  "data": null,
  "extensions": null
}

The mutation through Postman is:

{
  newBook(
    isn:"1",
    title: "test title",
    publisher: "test publisher",
    authors:"test author",
    publishedDate: "2 Nov 2018"
  ) {
    title
  }
}

Please help me out. Its not picking up the Mutation Type but Query is working absolutely fine. Am I missing anything?


Solution

  • I'm not sure what the error is referring to, but you do need to include the operation (query vs mutation) when performing a mutation. That is, your request should look more like this:

    mutation ArbitraryOperationName {
      newBook(
        isn:"1",
        title: "test title",
        publisher: "test publisher",
        authors:"test author",
        publishedDate: "2 Nov 2018"
      ) {
        title
      }
    }
    

    When writing queries, you can use the shorthand notation and omit the query keyword, but mutations must always include mutation to indicate that you are making a mutation and not a query.