GraphQL is a new way to build aN API using a strongly typed query language. Launched by Facebook in 2015, GraphQL is rapidly gaining traction and is being adopted by other large companies such as Twitter and Github. The GraphQL API is designed to be different from REST apis, and you can read this article “GraphQL and REST: Two API Architectures.”

In this article, we’ll take you through building a simple GraphQL API service using NodeJs

  • WEB services: Node
  • Database: Postgres
  • Data query:
    • express
    • apolo-server-express
    • Sequelize ORM
    • graphql schema language
    • graphql-sequelize

What is GraphQL?

GraphQL is both a query language for the API and a runtime for your data queries. GraphQL provides an easy-to-understand set of complete descriptions of the data in your API, enabling a client to get exactly what it needs without any redundancy, making it easier for the API to evolve over time, and for building powerful developer tools.

Simply put, it is a queryable model for apis that allows customers to request only the data they need, and provides a standardized system for designing apis without reference documentation.

GraphQL already has support for multiple programming languages. The following table contains some popular server frameworks, client libraries, services, and other useful content.

In addition to the GraphQL JavaScript reference implementation, there are other server-side libraries:

  • C# / .NET
  • Clojure
  • Elixir
  • Erlang
  • Go
  • Groovy
  • Java
  • JavaScript
  • PHP
  • Python
  • Scala
  • Ruby

Introduction: graphql. Cn /

Why GraphQL

The reason why I choose GraphQL is that many front-end projects need to acquire data through multiple API assembly to obtain the required data. When DESIGNING THE API, multiple application scenarios are often considered, resulting in redundant data obtained when a single scenario is used.

With this in mind, I was attracted to the idea of GraphiQL being able to declare a schema for data and let clients query the data as needed. Prefers to send the minimum number of requests over the network, group them together freely for the best payload, and cache them on both clients and servers.

The biggest benefit of GraphQL is that the request response is streamlined without redundant fields, and the front end can decide what data the back end returns. Of course, the decision of the front end depends on what data the back end supports, so GraphQL is more like REST with a simplified return value, and the back end interface can define all the functionality at once, rather than developing it individually.

The GraphQL API’s main application scenario is the API gateway, which provides an abstraction layer between the client and the service.

The Node service

Node was chosen as the server-side language because it has very strong community support around GraphQL and is highly portable.

With async/WAIT support in the new release, the synchronous model is easier to manage, which is a huge advantage when building highly asynchronous apis.

ORM to GraphQL adaptation

Graphql-sequelize, the code that maps the serialization model to graphQL types, queries, and updates. It provides two excellent abstractions:

  • Used to map GraphQL queries toSequelizeThe parser for the operation
  • Reuse the model definition as a list of GraphQL type fieldsattributeFieldsMapping.

GraphQL schema

Next create the query type as follows:

// Define query data type const managerType = new GraphQLObjectType({name: "manager", description: "A manager", fields: {id: { type: new GraphQLNonNull(GraphQLInt), description: "The id of the manager." }, username: { type: GraphQLString, description: "The username of the manager." }, password: { type: GraphQLString, description: "The password of the manager." }, email: { type: GraphQLString, description: "The email of the manager." } } }); // Define query interface const schema = new GraphQLSchema({query: new GraphQLObjectType({name: "root", fields: {managers: {type: new GraphQLList(managerType), resolve: resolver(manager) }, manager: { type: new GraphQLList(managerType), args: { username: { description: "username of the manager", type: new GraphQLNonNull(GraphQLString) } }, resolve: resolver(manager) } } }) });Copy the code

Web Server Framework

Express was chosen as the basic Web server framework because of its ubiquity in the node ecosystem, plug-in support, and simple apis.

Express allows you to listen to ports and respond to HTTP requests, but you need another layer to receive and respond to GraphQL requests.

Apollo-server-express, which has a very simple API and does some mapping to allow schemas to be defined in the node GraphQL schema language. As follows:

const express = require("express"); const { ApolloServer } = require("apollo-server-express"); const schema = require("./schema"); const server = new ApolloServer({ schema }); const app = express(); server.applyMiddleware({ app }); App.listen ({port: 3009}, () => console.log(' 🚀 Server ready at http://localhost:3009${server.graphqlPath} '));Copy the code

Debugging and documentation

Browser: http://localhost:3009/graphql, GraphiQL can easily make people feel “code document”.

Automatically generate interface documents

  • Query list data:

    { managers { username email } }

  • Query by condition:

    { manager(username:”QuintionTang”) { username email } }

AJAX call:

const { createApolloFetch } = require("apollo-fetch");

const fetch = createApolloFetch({
    uri: "http://localhost:3009/graphql"
});

fetch({
    query: "{ managers { username }}"
}).then(res => {
    console.log(res.data);
});

fetch({
    query: `{
        manager(username: "QuintionTang") {
        email
        id
      }
    }`
}).then(res => {
    console.log(res.data);
});
Copy the code

Client-side implementation

Common frameworks for clients are Relay and Apollo Client.

  • Relay is an official solution provided by Facebook

    The advantage of using Relay is that many GraphQL server-side frameworks support Relay standards (such as data paging interfaces).

  • Apollo is the most popular community for GraphQL

    Apollo-client’s implementation claims to be compatible with Relay’s style in many ways, so it should be used in much the same way.

conclusion

This paper is just a simple implementation, I feel the concept is very attractive, in a complex project can meet the expectations need to experience in the process of practice.