如何使用 Apollo Express 仅为 Graphql 后端中的特定解析器设置中间件?

how to set a middleware only for a specific resolver in Graphql backend using Apollo Express?

在 Rest API 中,如果你想为特定路由设置一个中间件,你可以使用这个,例如:

router
  .route('/top-5-cheap')
  .get(tourControllers.middleAliasApi, tourControllers.getAllTours);

所以在这种情况下,middleAliasApi 中间件只有在用户向该路由发送请求时才会执行。

我如何在 Graphql 应用程序中执行相同的操作? 例如,仅当用户查询特定解析器时才执行中间件。 我在后端使用 Apollo-express-server。

您可以使用 graphql-middleware 包。您可以为特定的解析器创建中间件。例如

const { ApolloServer } = require('apollo-server');
const { makeExecutableSchema } = require('@graphql-tools/schema');
const { applyMiddleware } = require('graphql-middleware');

// Minimal example middleware (before & after)
const beepMiddleware = {
  Query: {
    hello: async (resolve, parent, args, context, info) => {
      // You can use middleware to override arguments
      const argsWithDefault = { name: 'Bob', ...args };
      const result = await resolve(parent, argsWithDefault, context, info);
      // Or change the returned values of resolvers
      return result.replace(/Trump/g, 'beep');
    },
    tours: async (resolve, parent, args, context, info) => {
      const result = await resolve(parent, args, context, info);
      return result.concat([4]);
    },
  },
};

const typeDefs = `
  type Query {
    hello(name: String): String
    tours: [Int]!
  }
`;
const resolvers = {
  Query: {
    hello: (parent, { name }, context) => `Hello ${name ? name : 'world'}!`,
    tours: () => [1, 2, 3],
  },
};

const schema = makeExecutableSchema({ typeDefs, resolvers });

const schemaWithMiddleware = applyMiddleware(schema, beepMiddleware);

const server = new ApolloServer({
  schema: schemaWithMiddleware,
});

server.listen({ port: 8008 }).then(() => console.log('Server started at http://localhost:8008'));

查询结果:

⚡  curl -H 'Content-Type: application/json' -X POST -d '{"query": "{ tours }"}' http://localhost:8008/graphql
{"data":{"tours":[1,2,3,4]}}

包版本:

"graphql-middleware": "^3.0.3",
"apollo-server": "^2.15.1",