1. 程式人生 > >Fullstack React: GraphQL is fantastic. Here's how to write aGraphQL server

Fullstack React: GraphQL is fantastic. Here's how to write aGraphQL server

Hey Friend, it's Nate from Fullstack React.

love GraphQL and have found the client experience to be extremely pleasant.

GraphQL is a wonderful data query language that is used as an alternative to REST.

GraphQL Benefits

You may be wondering, "why anyone would prefer GraphQL over URL-centric APIs such as REST?" What do we get for the extra effort?

First, our API calls become easier to understand by declaring the exact data we want from the server. For a newcomer to a web app codebase, seeing GraphQL queries makes it immediately obvious what data is coming from the server versus what data is derived on the clients.

GraphQL is also designed with performance in mind, especially with respect to mobile clients. Specifying only the data needed in each query prevents over-fetching (i.e., where the server retrieves and transmits data that ultimately goes unused by the client). This reduces network traffic and helps to improve speed on size-sensitive mobile environments.

GraphQL dramatically improves the developer experience - its type system provides a living form of self-documentation, and tooling like GraphiQL (which we play with in this chapter) allow for natural exploration of a GraphQL server.

Finally, the declarative nature of GraphQL pairs nicely with the declarative nature of React. A few projects, including the Relay framework from Facebook, are trying to bring the idea of "colocated queries" in React to life.

Imagine writing a React component that automatically fetches the data it needsfrom the server, with no glue code around issuing API calls or tracking the lifecycle of a request.

Exploring With GraphiQL

GraphQL supports a visual IDE called GraphiQL. GraphiQL is developed by Facebook and can be used hosted on any GraphQL server with minimal configuration.

You can always issue GraphQL requests using tools like cURL or any language that supports HTTP requests, but GraphiQL is particularly helpful while you become familiar with a particular GraphQL server or GraphQL in general. It provides type-ahead support for errors or suggestions, searchable documentation (generated dynamically using the GraphQL introspection queries), and a JSON viewer that supports code folding and syntax highlighting.

Head to https://graphqlhub.com/playground and get your first look at GraphiQL and try entering the following query:

query {
  hn {
    topStories {
      url
      title
    }
  }
}

Writing your first GraphQL Server

Querying with GraphQL is interesting, but the real fun starts when we write our own GraphQL server from scratch.

Here's a preview of a minimal GraphQL server (which we explain step-by-step in the book, and build from there):

const app = express();

import graphqlHTTP from 'express-graphql';
import { 
  GraphQLSchema, 
  GraphQLObjectType, 
  GraphQLString 
} from 'graphql';

const RootQuery = new GraphQLObjectType({
  name: 'RootQuery',
  description: 'The root query',
  fields: {
    viewer: {
      type: GraphQLString,
      resolve() {
        return 'viewer!';
      }
    }
  }
});

const Schema = new GraphQLSchema({
  query: RootQuery
});

app.use('/graphql', graphqlHTTP({ schema: Schema }));

Reading a preview of the chapter

We've put up a preview of the Writing GraphQL Servers Chapter here. Check it out! Then download the newest version of the book to get the whole chapter (plus sample code)!

GraphQL is a super-powerful framework that more-and-more APIs will be using soon. I hope you like using GraphQL as much as I do.

Talk to us!

If you have any questions, need clarification, help, or just want to say "hi" email us!We'd love to hear from you: [email protected]

We tweet on occasion about React and the Fullstack React book here at the @fullstackreact Twitter account. If you're a Twitter user, we love to chat with you there.

Nate

P.S.

  • How to use Express to write a server that accepts GraphQL requests
  • How to construct a GraphQL schema
  • Write the glue-code that resolves data for each GraphQL field in our schema
  • Support GraphiQL so we can debug and iterate quickly
  • How to write mutations to modify data on our server
  • How to add authentication and authorization to our GraphQL queries
  • How to optimize your GraphQL queries using DataLoader batching