4

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?

1 Answers1

7

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

Stephen Crosby
  • 1,157
  • 7
  • 19
  • 1
    Thanks for your answer! I would like to dump my schema in a `schema.json` and use this file to generate typescript interfaces with `graphql-code-gen`. If there is a custom scalar type, is it possible to generate a Typescript Interface which looks like the `NodeDescription`? My feeling says it is impossible :/ – Yannick Schröder May 29 '20 at 08:18
  • I'm not familiar with graphql-code-gen, but it might be possible. I did a search for "graphql-code-gen custom scalars" and found some results that look more or less like what you want to do. – Stephen Crosby Aug 11 '21 at 16:37