I am trying to setup mutations in my Rails app, so I followed the guides and I have in my graphql/mutations folder:
Mutations::MutationType = GraphQL::ObjectType.define do
name "Mutation"
field :addPlace, Types::PlaceType do
description "Adds new place!"
argument :place, PlaceInputType
resolve -> (t, args, c) {
Place.create(args[:place])
}
end
end
PlaceInputType = GraphQL::InputObjectType.define do
name "PlaceInputType"
description "Properties for creating a Place"
argument :title, !types.String do
description "Title of the Place."
end
argument :description, !types.String do
description "Description of the Place."
end
end
And I try to run mutation in graphiql like this:
mutation {
addPlace(place: {title: "Place title", description: "Place description"}) {
id
title
}
}
All I get in the right graphiql console is SyntaxError: Unexpected token < in JSON at position 0, and in my rails console I also get an error saying ArgumentError (When assigning attributes, you must pass a hash as an argument.).
What did I do wrong?
args[:place] returns a GraphQL::Query::Arguments instance. To convert it to a Hash, use .to_h, for example:
Place.create(args[:place].to_h)
Does that fix it for you?
@rmosolgo It actually does. Brilliant! It really should be included in the examples click, as it seems like to_h is happening behind the curtains.
Thanks for that!
Oh, you're right, those examples should be improved! Glad it worked for you :)
Note: The examples are still incorrect and by today you still need to append .to_h. At least that is what worked for me fro brand new app.
Most helpful comment
args[:place]returns aGraphQL::Query::Argumentsinstance. To convert it to a Hash, use.to_h, for example:Does that fix it for you?