所以我的用例看起来非常简单,但我却在苦苦思索如何才能做到这一点。
从本质上来说,我想开发一个 gatsby-plugin
修改了所有与内容相关的graphQL查询,使其始终能插入 contentful_id
所以返回的数据总是包含该字段。这样一来,我的插件的消费者就不必再为我的插件添加 contenful_id
字段的所有grapqhQL查询。
这是可行的吗?我对创建字段不感兴趣,因为我相信它们不会成为返回数据的一部分,除非你明确地添加该字段。
的方式来做。
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 || '';
},
},
};
};