我正在模块化GraphQL API的模式,并尝试在不使用任何第三方库的情况下合并解析器 .
没有 Lodash.merge()
或同等的方法,有没有一种简单的方法可以做到这一点?
Apollo文档说要使用像Lodash这样的库到 merge()
模块化解析器 . (http://dev.apollodata.com/tools/graphql-tools/generate-schema.html#modularizing)
问题似乎是,就其本质而言,解析器包含函数作为属性,因此当我通过 Object.assign()
甚至 JSON.stringify()
访问它们时它们似乎被省略了 .
如果我console.log他们,我看到: {"Query":{},"Mutation":{}}
以下是其中一个解析器的样子:
const productResolvers = {
Query: {
myProducts: (root, { userId }, context) => {
return [
{ id: 1, amount: 100, expiry: '12625383984343', created: '12625383984343' },
{ id: 2, amount: 200, expiry: '12561351347311', created: '12625383984343' },
{ id: 3, amount: 200, expiry: '11346347378333', created: '12625383984343' },
{ id: 4, amount: 350, expiry: '23456234523453', created: '12625383984343' },
];
},
},
Mutation: {
addProduct: (root, { userId }, context) => {
return { id: 350, amount: 100, expiry: '12625383984343', created: '12625383984343' };
},
}
};
让我们假设还有一个几乎完全相同的叫 widgetResolvers
.
这是一个功能齐全的代码块:
export const schema = makeExecutableSchema({
typeDefs: [queries, mutations, productSchema, widgetSchema],
resolvers
});
这是我想要实现的目标:
export const schema = makeExecutableSchema({
typeDefs: [queries, mutations, productSchema, widgetSchema],
resolvers: Object.assign({}, productResolvers, widgetResolvers)
});
我还没有加载使用休息传播的能力(https://babeljs.io/docs/plugins/transform-object-rest-spread/) . 我怀疑它不会出于同样的原因 Object.assign()
不起作用 .
哦,这就是为什么我怀疑这个合并不起作用的原因:Why doesn't JSON.stringify display object properties that are functions?
1 回答
如果您正在使用
Object.assign()
,那么您的查询和突变属性不应该't end up empty, but you will run into an issue because, unlike lodash' smerge()
,它不是递归的 .Object.assign()
仅比较它传递的对象的"direct"属性 - 覆盖先前源在列表中移动时的属性 .因为
Query
和Mutation
是要传递的对象的属性,所以每个后续解析器都会覆盖前一个对象的Query
和Mutation
,结果对象只保存传递到Object.assign()
的最后一个对象的Query和Mutation属性 .它不那么整洁,但是如果你一直想要避免导入lodash,你可以通过这种方式得到预期的行为:
有类型解析器吗?没问题: