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?
Essentially, apollo-server is still a middleware that bridges the HTTP layer with the GraphQL engine provided by GraphQL.
The way we set up a GraphQL server using apollo-server-express is very similar to the barebones approach of using the apollo-server package. The only difference is that we apply the Apollo Server instance as middleware to an Express HTTP instance with server.
You will need three top-level dependencies for your application to run: apollo-server-express: the Express integration that comes with GraphQL Server. graphql: the library you'll use to build a GraphQL schema and execute queries. express: in charge of server-side logic for web apps.
Apollo Server provides:Straightforward setup, so your client developers can start fetching data quickly. Incremental adoption, enabling you to add features as they're needed. Universal compatibility with any data source, any build tool, and any GraphQL client.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With