You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

express-graphql中如何在query解析后resolver执行前添加自定义逻辑

express-graphql 实现resolver执行前打印info对象的方案

express-graphql 本身没有内置query:parsed这类解析完成、resolver执行前的全局事件钩子,你可以通过以下两种方式实现需求:

方案1:针对性包装指定resolver(推荐,符合你只需要两个查询字段的需求)

你可以编写一个高阶函数,对需要打印日志的products和productByHandle的resolver进行包装,在调用原始resolver前先执行打印info的逻辑:

// 高阶resolver包装函数,所有需要加前置逻辑的resolver都可以用它包裹
const withPreResolverLog = (originalResolver) => {
  return async (parent, args, context, info) => {
    // 自定义前置逻辑:打印当前字段的info对象
    console.log(`[${info.fieldName}] 执行前info对象:`, info);
    // 执行原始resolver逻辑
    return originalResolver(parent, args, context, info);
  };
};

在你的resolver定义处直接使用包装函数即可:

const resolvers = {
  Query: {
    // 用withPreResolverLog包裹原有的products resolver
    products: withPreResolverLog(async (parent, args, context, info) => {
      // 原有products查询逻辑
    }),
    // 用withPreResolverLog包裹原有的productByHandle resolver
    productByHandle: withPreResolverLog(async (parent, args, context, info) => {
      // 原有productByHandle查询逻辑
    })
  }
};

方案2:全局批量包装所有resolver

如果你后续需要给所有字段的resolver都加上前置逻辑,不需要逐个手动包装,可以遍历schema的所有字段统一处理:

const { GraphQLObjectType } = require('graphql');

// 全局批量包装resolver的工具函数
const batchWrapResolvers = (schema, wrapperFunc) => {
  const allTypes = schema.getTypeMap();
  Object.values(allTypes).forEach(type => {
    if (type instanceof GraphQLObjectType) {
      const fields = type.getFields();
      Object.values(fields).forEach(field => {
        if (field.resolve) {
          field.resolve = wrapperFunc(field.resolve);
        }
      });
    }
  });
  return schema;
};

// 使用示例:把构造完成的原始schema和上面的withPreResolverLog函数传入即可
const processedSchema = batchWrapResolvers(yourRawSchema, withPreResolverLog);

补充说明

如果后续可以换GraphQL服务框架,apollo-server-express提供了插件的willResolveField钩子,原生支持在任意字段resolver执行前触发自定义逻辑,不需要手动包装resolver。

内容的提问来源于stack exchange,提问作者Diyan Slavov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:15:04