简体   繁体   中英

How to define recursive GraphQL type programmatically?

Let's say, for example, I want to define a typical forum message type using GraphQL JavaScript interface:

import {
  GraphQLString,
  GraphQLObjectType,
} from 'graphql';

const MessageType = new GraphQLObjectType({
  name: 'Message',
  fields: {
    text: { type: GraphQLString },
    comments: new GraphQLList(MessageType),
  },
});

The JavaScript compiler (well, interpreter) would complain about this. It would say that MessageType is undefined .

We all know it is possible to define such a type using the GraphQL language:

type Message {
    text: String
    comments: [Message]
}

How could you define such a type using GraphQL pure JavaScript interface?

Well, the answer is simple.

You just need to pass a thunk (function without arguments) as the field field instead of passing plain JavaScript object.

The function would be executed only when the type would already be defined, so, it will work.

Resulting code looks like this:

import {
  GraphQLString,
  GraphQLObjectType,
} from 'graphql';

const MessageType = new GraphQLObjectType({
  name: 'Message',
  fields: () => ({  // <-- Notice the function definition
    text: { type: GraphQLString },
    comments: new GraphQLList(MessageType),
  }),
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM