Why isn't Apollo Server a middleware for Express, rather than being a server that accepts Express as a middleware?

偶尔善良 提交于 2019-12-06 00:54:19

问题


I'm just wondering what's the reason for this seemingly awkward configuration (from Getting Started w/ Apollo Server),

const server = new ApolloServer({
  // These will be defined for both new or existing servers
  typeDefs,
  resolvers,
});

server.applyMiddleware({ app }); // app is from an existing express app

Why is that I'm calling .applyMiddleware() and feeding it my app rather than using app.use(), it even seems from the docs that Apollo is only answering requests on /graphql wouldn't it be better to follow the Express API of,

let apollo = require('apollo-server').ApolloMiddleware
app.use( '/graphql', apollo({ typeDefs, resolvers }) );

It seems like Apollo is inverting the normal middleware flow of Express? What is the advantage of doing it the Apollo way?


回答1:


I don't work with those guys, but based off the code that is there, I assume it has to do with the fact that it adds body-parser, upload capability, websockets (if you opt into this one) to the app, as well as a .well-known configuration for engine's health checks. The well-known would have to be at root according to that spec. Additionally, if you're using the subscriptions and websockets, they listen for httpServer.once('listening'), so they have to have access to your app. If they simply handed you one that you could mount, you wouldn't app.listen on it, since you'd app.listen on your own instead.

Just from the internals, this is what I would expect, at least.



来源:https://stackoverflow.com/questions/51716013/why-isnt-apollo-server-a-middleware-for-express-rather-than-being-a-server-tha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!