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'
}]
}]
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?
答案 0 :(得分:7)
引自官方文件
http://graphql.org/docs/api-reference-type-system/
当两种类型需要相互引用时,或者需要引用类型时 在字段中,您可以使用函数表达式(也称为闭包) 或者是一个懒洋洋的人来懒洋洋地供应田地。
a1=cell2mat(final(:,3)); %numeric data, variable 1 to save
no=cell2mat(final(:,4));
a2=zeros(numel(a1),1); %temporary variable
for i=1:numel(a2);
if no(i)~=1;
a2(i)=no(i);
end
end
a3=a1+a2; %numeric data, variable 2 to save
fid = fopen( 'results.txt', 'wt' );
for i=1:length(no);
fprintf(fid, '%f %f %s\n',a1(i),a3(i),char(final(i,2)));
end
fclose(fid);
另请参阅循环类别 - 子类别
的相关answer答案 1 :(得分:0)
我通过在字段字段中使用thunk解决了这个问题。
const User = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: GraphQLID }
})
});
当您将字段设置为thunk而不是对象文字时,可以使用稍后在文件中定义的类型。
请参阅此帖子了解更多信息Is there a way to avoid circular type dependencies in GraqhQL?
基于该帖子,我认为这是正确的方法。