所以我的用例看起来很简单,但我正在努力弄清楚如何才能做到这一点。
本质上,我想开发一个gatsby-plugin,它可以修改所有与内容相关的graphQL查询,使其始终插入contentful_id,以便返回的数据始终包含该字段。这样,我的插件的使用者就不必在所有的grapqhQL查询中添加contenful_id字段了。
这是可行的吗?我对创建字段不感兴趣,因为我认为除非显式添加该字段,否则它们不会成为返回数据的一部分。
发布于 2020-05-26 02:15:10
这样做的方法是:
graphql SDK访问节点。这样定义一个访问者:const { print, visit, parse } = require('graphql');
const visitor = {
SelectionSet(node, key, parent) {
if (!isQuery(parent) && !isFragment(parent)) {
node.selections.push({
kind: 'Field',
name: { kind: 'Name', value: 'yourFieldName' },
});
}
},
};
function isQuery(node) {
return node.kind === 'OperationDefinition' && node.operation === 'query';
}
function isFragment(node) {
return node.kind === 'FragmentDefinition';
}然后访问
const result = visit(parse(queryAST), { enter: visitor });
return print(result);exports.setFieldsOnGraphQLNodeType = () => {
return {
yourFieldName: {
type: GraphQLString,
resolve: (source) => {
return source.contentful_id || '';
},
},
};
};https://stackoverflow.com/questions/61959904
复制相似问题