Home > Software design >  What is the proper way to use Graphql JSON Scalar in Rails?
What is the proper way to use Graphql JSON Scalar in Rails?

Time:10-19

I have a type that looks like this:

module Types
  class LeadType < Types::BaseObject
    graphql_name 'Lead'
    description 'A lead data query selection'
    field :first_name, String, null: true
    field :last_name, String, null: true
    field :email, String, null: true
    field :gender, String, null: true
    field :errors, [String], null: true
    field :success, String, null: true
    field :lead, Types::LeadType, null: true

    field :home_data, GraphQL::Types::JSON, null: false
  end
end

Note how I have field :home_data, GraphQL::Types::JSON, null: false

Now, when pulling my query data, it's a raw JSON like so:

{
  "success"=>true,
  "lead"=>
  {
    "home"=>
    {
      "1"=>
        {
          "roof"=>"GRAVEL",
          "garage"=>"Yes",
          "dead_bolt"=>"No",
          "effective"=>"2022-08-25",
          "sprinkler"=>"No"
        }
    },
    "first_name"=>"John",
    "last_name"=>"Doe",
    "email"=>"[email protected]",
    "phone"=>"5599999777",
    "gender"=>"Male"
  }
}

Now I am able to query my data without the field:home_data, GraphQL::Types::JSON enter image description here

But when I add the homeData to playground I have this error:

enter image description here

Now, I need the field :home_data, GraphQL::Types::JSON, null: false to display the:

"home"=>
        {
          "1"=>
            {
              "roof"=>"GRAVEL",
              "garage"=>"Yes",
              "dead_bolt"=>"No",
              "effective"=>"2022-08-25",
              "sprinkler"=>"No"
            }
        }

How I am able to achieve this using GraphQL::Types::JSON?

CodePudding user response:

null: false means the field is non-nullable. This means that the field will never be nil. If the implementation returns nil, GraphQL-Ruby will return an error to the client

So if your request contains homeData field - your data must contain home_data JSON. But it doesn't. You have home key, not home_data

  • Related