Search code examples
ruby-on-railsgraphqlrails-console

How can I run a Graphql query in a Rails console?


I have a Graphql query working in Graphiql:

query MyConfigurationType {
  myConfiguration {
    number
    expirationDate
  }
}

Returns

{
  "data": {
    "myConfiguration": {
      "number": 1,
      "expirationDate": "2022/10/04"
    }
  }
}

But I need to actually use that result in my app therefore I want to be able to run it in my rails console. There doesn't seem to be much info about this.

How would one go about executing a Graphql query in the Rails console?


Solution

  • After looking at some documentation the best I could manage to do was, in the Rails console do:

    query_string = "query MyConfigurationType {
      myConfiguration {
        number
        expirationDate
      }
    }"
    

    and the run

    result = MySchema.execute(query_string)
    

    Which has a result of

    => #<GraphQL::Query::Result @query=... @to_h={"data"=>{"myConfiguration"=>{"number"=>1, "expirationDate"=>"2022/10/04"}}}>
    

    Therefore one can now do

    [1] pry(main)> result['data']
    => {"myConfiguration"=>{"number"=1, "expirationDate"=>"2022/10/04"}}