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

查看:138
本文介绍了使用循环引用动态创建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
}

如何我解决了吗?

推荐答案

引用自官方文档

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天全站免登陆