通过使用graphql-js,我需要通过迭代一些数据数组来动态创建graphql模式,例如:
[{
name: 'author',
fields: [{
field: 'name'
}, {
field: 'books',
reference: 'book'
}]
}, {
name: 'book',
fields: [{
field: 'title'
}, {
field: 'author',
reference: 'author'
}]
}]
问题是循环引用。创建AuthorType时,我需要已经创建BookType,反之亦然。
因此,生成的架构应类似于:
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)来延迟提供字段。
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 },
})
});
另请参阅循环类别-子类别类型的相关答案
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句