我正在研究GraphQL
,在撰写fields
的{{1}}时,我对特定问题的不同实施方式感到有些困惑。
这两种实现有什么区别?
1
GraphQLObjectType
2
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: { // as object
echo: {
type: GraphQLString,
args: {
email: { type: EmailType }
},
resolve: (root, {email}) => {
return email;
}
}
}
})
});
答案 0 :(得分:2)
答案 1 :(得分:0)
这是CLOSURE的一个很好的例子。假设您在文件中有两种类型,并且它们相互引用。
const BookType= new GraphQLObjectType({
name: 'BookType',
fields: { // as object
author: {
type: AuthorType,
resolve: (parentValue, args) => {
// query the author based on your db implementation.
}
} }
})
BookType具有一个字段作者,并引用 AuthorType 。现在,假设您在引用 BookType
的“ BookType”下定义了AuthorTypeconst AuthorType= new GraphQLObjectType({
name: 'AuthorType',
fields: { // as object
books: {
type: new GraphQLList(BookType), //one author might have multiple books
resolve: (parentValue, args) => {
// query the books based on your db implementation.
}
} }
})
因此,当Javascript引擎需要使用BookType
时,将看到fields.author.type
是AuthorType,而AuthorType在上面没有定义。这样会给
reference error:AuthorType is not defined
为避免这种情况,我们将字段转换为函数。此函数是CLOSURE函数。这是一个很好的例子,说明了闭包如此有用的原因。
当js引擎首先读取文件时,它会将函数内部引用的所有变量保存到内存堆中,作为该函数的关闭存储。 BookType.fields
所需的所有变量都存储在BookType.fields()的关闭环境中。因此,现在,如果javascript执行Booktype.fields(),它将检查是否在函数内部定义了“ AuthorType”,但尚未定义,因此它会检查其闭包存储, AuthorType 已在开始存储,因此它会使用它。