MERN Stack & GraphQL - #2 Express GraphQL Server
GraphQL.js allows for a GraphQL integration with Node.js, but it's only one piece of a puzzle. Many web apps in Node are built with a framework, such as Express. To host a GraphQL API service on an Express web server, we would need to pull in another dependency known as express-graphql (https://github.com/graphql/express-graphql). It exposes an HTTP middleware that allows to mount a GraphQL server to an endpoint. As a side note, you could also use express-graphql with Restify as well. Just like before, we'll define our schema using GraphQL SDL and write out resolver functions in the rootValue object. For development, we'll also enable GraphiQL, which is a handy browser tool for interacting with GraphQL. As you're going to see, a GraphQL query is nothing but a POST (in Apollo Server, a POST or a GET) request to /graphql endpoint, where the body payload contains the JSON formatted query string with optional variables. The response from the GraphQL web service is a JSON object containing the "data" key, as well as a data structure mirroring the user requested query. You could easily issue a query with a curl command, or even an AJAX request, using the native fetch API or a 3rd party lib, like axios. In fact, GraphQL clients, including urql, Apollo Client, or Relay, work exactly by that principle, though they often offer extra functionality on top, such as caching or state management. As good as it is, express-graphql is not very flexible with composite types. Most apps have intertwined relationships between resources; for instance, in a blog site, users have posts, posts have comments, and comments have likes, etc. Unless you can rely on a perfect 1 to 1 mapping with your ORM, if it allows for it, your only options are to - default back to the verbose (and IMO, messy) object-based approach (https://graphql.org/graphql-js/constructing-types) where it's easy to mix up your schema with the business logic, or - stick with the GraphQL SDL and root level resolvers, but wrap your data entities with ES6 model classes, where you define getter methods for custom properties and relationships. The latter can certainly work, but there's a better game in town. We'll explore a more modularized and cleaner approach next. Stay tuned! GraphQL SDL — Schema Definition Language https://blog.graph.cool/graphql-sdl-schema-definition-language-6755bcb9ce51 Running an Express GraphQL Server https://graphql.org/graphql-js/running-an-express-graphql-server graphqlHTTP middleware options https://github.com/graphql/express-graphql#options
Download
0 formatsNo download links available.