【问题标题】:how to set a middleware only for a specific resolver in Graphql backend using Apollo Express?如何使用 Apollo Express 仅为 Graphql 后端中的特定解析器设置中间件?
【发布时间】:2021-12-04 14:03:41
【问题描述】:

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

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

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

我怎样才能在 Graphql 应用程序中做同样的事情? 例如,仅当用户查询特定解析器时才执行中间件。 我在后端使用 Apollo-express-server。

【问题讨论】:

    标签: node.js express graphql apollo apollo-server


    【解决方案1】:

    您可以使用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",
    

    【讨论】:

      猜你喜欢
      • 2018-03-12
      • 2018-02-18
      • 2017-01-11
      • 2017-05-04
      • 2019-05-02
      • 2020-07-22
      • 2018-02-16
      • 2021-07-29
      • 2021-03-25
      相关资源
      最近更新 更多