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

如何我解决了吗?

推荐答案

引用自官方文档



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模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!