【问题标题】:Gatsby: Inject a field in a graphql query before executing it within a pluginGatsby:在插件中执行之前在 graphql 查询中注入一个字段
【发布时间】:2020-09-09 13:58:38
【问题描述】:
所以我的用例看起来很简单,但我正在努力弄清楚我该怎么做。
本质上,我想开发一个gatsby-plugin 来修改所有与内容相关的graphQL 查询以始终插入contentful_id,因此返回的数据始终包含该字段。这样,我的插件的使用者就不必在所有 grapqhQL 查询中添加 contenful_id 字段。
这甚至可行吗?我对创建字段不感兴趣,因为我相信除非您明确添加该字段,否则它们不会成为返回数据的一部分。
【问题讨论】:
标签:
node.js
plugins
graphql
gatsby
inject
【解决方案1】:
方法:
- 使用
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 || '';
},
},
};
};