使用循环引用动态创建 graphql 模式 [英] Dynamically creating graphql schema with circular references

查看:33
本文介绍了使用循环引用动态创建 graphql 模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用graphql-js,我需要通过迭代一些数据的数组来动态创建graphql模式,例如:

By using graphql-js, I need to create graphql schema dynamically by iterating over array of some data, for example:

[{
    name: 'author',
    fields: [{
        field: 'name'
    }, {
        field: 'books',
        reference: 'book'
    }]
}, {
    name: 'book',
    fields: [{
        field: 'title'
    }, {
        field: 'author',
        reference: 'author'
    }]
}]

问题是循环引用.当我创建 AuthorType 时,我需要已经创建 BookType,反之亦然.

The problem is circular references. When I'm creating AuthorType I need BookType to be already created and vise versa.

因此结果架构应该如下所示:

So resulting schema should look like:

type Author : Object {  
  id: ID!
  name: String,
  books: [Book]
}

type Book : Object {  
  id: ID!
  title: String
  author: Author
}

我该如何解决这个问题?

How can I solve this?

推荐答案

引自官方文档

http://graphql.org/docs/api-reference-type-system/

当两个类型需要相互引用,或者一个类型需要引用时对于字段中的自身,您可以使用函数表达式(又名闭包或 thunk) 懒惰地提供字段.

When two types need to refer to each other, or a type needs to refer to itself in a field, you can use a function expression (aka a closure or a thunk) to supply the fields lazily.

var AddressType = new GraphQLObjectType({
  name: 'Address',
  fields: {
    street: { type: GraphQLString },
    number: { type: GraphQLInt },
    formatted: {
      type: GraphQLString,
      resolve(obj) {
        return obj.number + ' ' + obj.street
      }
    }
  }
});

var PersonType = new GraphQLObjectType({
  name: 'Person',
  fields: () => ({
    name: { type: GraphQLString },
    bestFriend: { type: PersonType },
  })
});

另请参阅循环类别的此相关答案-子类别类型

Also look at this related answer of circular Category-Subcategory types

这篇关于使用循环引用动态创建 graphql 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆