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



在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",

相关内容

  • 没有找到相关文章

最新更新