简体   繁体   English

如何以编程方式定义递归GraphQL类型?

[英]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: 比方说,我想使用GraphQL JavaScript接口定义一个典型的论坛消息类型:

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. JavaScript编译器(好吧,解释器)会抱怨这个。 It would say that MessageType is undefined . 它会说MessageType is undefined

We all know it is possible to define such a type using the GraphQL language: 我们都知道可以使用GraphQL语言定义这样的类型:

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

How could you define such a type using GraphQL pure JavaScript interface? 你如何使用GraphQL纯JavaScript接口定义这样的类型?

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. 您只需要将thunk(无参数的函数)作为field字段传递,而不是传递纯JavaScript对象。

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),
  }),
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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