What is GraphQL?

GraphQL is both an API query language 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.

GraphQL is a query language for apis, a server-side runtime that executes queries using a type based system (defined by your data). GraphQL isn’t tied to any particular database or storage engine, but relies on your existing code and data.

About SQL

SQL is a Structured Query Language.

To use SQL in your web site, for example, to create a web site that displays data from a database, you need:

1, RDBMS database programs (such as MS Access, SQL Server, MySQL)

2. Use server-side scripting languages (such as PHP, ASP, Node)

3. Use SQL to get the data you want

4、使用 HTML / CSS

How to use

GraphQL is an API syntax that describes how a client requests data from a server, similar to the RESTful API specification.

A client can send a request via HTTP GET, which is structured as follows:

http://myapi/graphql? query={me{name}}
Copy the code

Then your GraphQL HTTP server should be able to handle HTTP GET methods.

// server.js
const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const schema = require('./schema')
const cors = require('cors')

const app = express()
app.use(cors({
  origin: 'http://localhost:3000'.methods: 'GET,POST,OPTIONS,DELETE,PUT'
}))
app.use('/graphql', graphqlHTTP({
  schema,
  graphiql: true
}))
app.listen(4000.() = > {
  console.log('Server startup: http://localhost:4000')})Copy the code

The EXPRESs-GraphQL NPM package is used to create a GraphQL HTTP service. Use it in conjunction with regular Express to run GraphQL to process requests and then return data.

The NPM package for GraphQL is a syntactic implementation of the GraphQL specification for running in a Node.js environment. The GraphQL API is organized based on types and fields. So the purpose of this package is to define types and fields and provide API methods.

// schema.js
const graphql = require('graphql')
const { GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLList, GraphQLNonNull } = graphql

const User = new GraphQLObjectType({
  name: 'User'.fields: () = > ({
    id: { type: GraphQLString },
    name: { type: GraphQLString }
  })
})

const UserInfo = { id: "1".name: "Zhang" }

const RootQuery = new GraphQLObjectType({
  name: 'RootQuery'.fields: {
    me: {
      type: User,
      args: {
        / / parameters
      },
      resolve (parent, args) {
        return UserInfo
      }
    }
  }
})

module.exports = new GraphQLSchema({
  query: RootQuery
})
Copy the code

Then start the service when we access the following address:

http://localhost:4000/graphql?query={me{name}}
Copy the code

The following results are displayed:

{
  "data": {
    "me": {
      "name": "Zhang"}}}Copy the code

GraphQL is primarily for data interfaces, such as front-end and back-end interactions. The client can filter freely to obtain the data defined by the server, which improves the flexibility of the interactive interface. For example, the above interface only has the name field, and now I want to access the ID field, just need to bring the fields you want to obtain when the interface request.

http://localhost:4000/graphql?query={me{name,id}}
Copy the code

Send a GraphQL request to your API to get exactly the data you want, no more, no less. GraphQL queries always return predictable results. Applications using GraphQL work fast and reliably because our application, not the server, controls the data.

GraphQL queries can not only retrieve the attributes of a resource, but also further query along inter-resource references. While typical REST apis load multiple urls to request multiple resources, GraphQL can get all the data you need for your application in a single request. As a result, applications using GraphQL are fast enough to perform even over slow mobile connections.

const graphql = require('graphql')
const { GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLList, GraphQLNonNull } = graphql

const categories = [
  { id: '1'.name: 'book' },
  { id: '2'.name: 'mobile phone' },
  { id: '3'.name: 'bread' },
  { id: '4'.name: 'computer'},]// products.category corresponds to categories. Id represents the category ID
const products = [
  { id: '1'.name: 'Simple nodeJS'.category: '1' },
  { id: '2'.name: 'Advanced programming'.category: '1' },
  { id: '3'.name: Huawei Mobile phone.category: '2' },
  { id: '4'.name: 'MAC'.category: '4'},]const Category = new GraphQLObjectType({
  name: 'Category'.fields: () = > ({
    id: { type: GraphQLString },
    name: { type: GraphQLString },
    products: {
      type: new GraphQLList(Product),
      resolve (parent) {
        // parent is the current category, based on which to find the corresponding product list
        return products.filter(item= > item.category === parent.id)
      }
    }
  })
})

const Product = new GraphQLObjectType({
  name: 'Product'.fields: () = > ({
    id: { type: GraphQLString },
    name: { type: GraphQLString },
    category: {
      type: Category,
      resolve (parent) {
        // category: '1
        return categories.find(item= > item.id === parent.category)
      }
    }
  })
})


// Define the root type
const RootQuery = new GraphQLObjectType({
  name: 'RootQuery'.fields: {
    // Query categories by ID
    getCategory: {
      type: Category,
      args: {
        id: { type: GraphQLString },
      },
      resolve (parent, args) {
        return categories.find((item) = > item.id === args.id)
      }
    },
    // Query all categories
    getCategoryList: {
      type: new GraphQLList(Category),
      args: {
      },
      resolve (parent, args) {
        return categories
      }
    },
    // Query the product by ID
    getProduct: {
      type: Product,
      args: {
        id: { type: GraphQLString },
      },
      resolve (parent, args) {
        return products.find((item) = > item.id === args.id)
      }
    },
    // Query all products
    getProductList: {
      type: new GraphQLList(Product),
      args: {
      },
      resolve (parent, args) {
        return products
      }
    }
  }
})

module.exports = new GraphQLSchema({
  query: RootQuery
})
Copy the code

There are multiple products under one category, this one-to-many relationship. When we query a category, we can also find out the list of products in a specific category. This association is the characteristic of further query along the reference between resources.

You can check out the complete example code on GitHub: Links. For more details, see the official documentation: Links