GraphQL: Representing nested types


#1

How do you represented nested types in reasonML? my apollo query returns:
worldcup {
host: country
}

country{
name: string
hostedWorldCups: worldcup
}

But If I try:

type worldcup = {
    year: int,
    name: string,
    host: country,
  };

  type country = {
    id: option(string),
    code: option(string),
    name: option(string),
    hostedWorldCups: list(worldcup),
  };

I get an Error: Unbound type constructor country how should I represent this nested types?


#2

Generally speaking, if you define two types that depend on each other in Reasonml, you’ll probably want to define them recursively. For this case, that may look like:

type country = {
  id: option(string),
  code: option(string),
  name: option(string),
  hostedWorldCups: list(worldcup)
} and worldcup = {
    year: int,
    name: string,
    host: country
};

Actually applying the results of the query to predefined types is something I’m not too sure of - I’ve just been using the open object type in my own components.


#3

Hey @hackersapien, take a look at this page on converting between reason records and JS objects.

By declaring your worldcup and country types like:

[@bs.deriving jsConverter]
type worldcup = {
    year: int,
    name: string,
    host: country,
  } [@bs.deriving jsConverter] and country = {
    id: option(string),
    code: option(string),
    name: option(string),
    hostedWorldCups: list(worldcup),
  };

This allows exports a pair of utility functions countryFromJs and worldcupFromJs that you can map over your Apollo query response and convert to Reason records. Hope that helps!