ruby-on-railsrubygraphqlgraphql-rubygraphql-schema

Graphql-ruby how to define a hash as type


Is there a possibility to define a Hash as Type field in graphql-ruby schema? In my data structure there is a multi language String type, which consist out of the language code as key and a corresponding text. At the Moment there are 2 languages provided like:

{ 
  "en" : "hello",
  "de" : "hallo"
}

So it is enough to build a type like that:

 class Types::LanguageStringType < GraphQL::Schema::Object
   field :de, String, null:true
   field :en, String, null:true
 end

How does a type looks like which provides a Map of String to String? The corresponding typescript interface looks like this for example:

title: {
  [language: string]: string;
}

To make a step further, like a recursive node:

export interface NodeDescription {
  name: string
  children?: {
      [childrenCategory: string]: NodeDescription[];
  }
}

Is there a way to use this in a field as a Types::NodeDescriptionType in graphql-ruby schema?


Solution

  • There is no such thing as a generic object type. And there is no built-in String -> String Hash type. Your GraphQL API is built on a specific object graph which you have to define in advance. If all you want is a String -> String Hash, then you may be able to define your own scalar, or if its sufficient you could use the built-in JSON scalar that comes with graphql-ruby:

    Source: https://graphql-ruby.org/type_definitions/scalars.html