GraphQL Quick Start Tutorial

Abstract: Experience the magic of GraphQL!

Fundebug authorized reprint, belongs to original author.

GraphQL Profile

definition

Data query language for API calls

main idea

The traditional general api calls to get the back end is assembled a complete object, and the front end may require only some of the fields, queries and work most of the data transmission are wasted. graphQL provide a new data query, you can get only the data needed to make api calls a more flexible, efficient and low cost.

Feature

  1. What you need to get what data
  2. Support for relational data queries
  3. No definition API various routing, data driver completely
  4. No management API version, a version of the continuing evolution
  5. It supports most popular development languages ​​and platforms
  6. Powerful development tools,

Instructions

Let's build a by SpaceX news site intuitively learn the basic use graphQL all data from the official API available.

GraphQL server

Server using node + express. A new node item, install the following dependence:

$ npm i graphql express-graphql express axios

Create a file entry server.js, which created express service. Use graphQL we only need to set up a route, all requests by the request handler to deal with this graphQL of:

const express = require("express");
const graphqlHTTP = require("express-graphql");
const schema = require("./schema");

const app = express();

app.use(
    "/graphql",
    graphqlHTTP({
        schema,
        graphiql: true
    })
);

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

graphqlHTTP is grapql the http service for processing graphql query request, it receives a parameter options, which the schema is an GraphQLSchemaexample, we are going to define, graphiql set to true graphQL can debug directly in the browser. More express-graphql usage, please refer to Github express-graphql .

schema

Next we define the schema, schema which means 'model', which defines the relationship between the structure of the data model, the type of field, the model is the core of graphQL.

New schema.jsfile, first define two data models: LaunchType (transmitter) and RocketType (rockets). Note that the field data type requires the use GraphQL defined, it can not be used in the basic data types js.

const {
    GraphQLObjectType,
    GraphQLInt,
    GraphQLString,
    GraphQLBoolean,
    GraphQLList,
    GraphQLSchema
} = require("graphql");

const LaunchType = new GraphQLObjectType({
    name: "Launch",
    fields: () => ({
        flight_number: { type: GraphQLInt },
        mission_name: { type: GraphQLString },
        launch_date_local: { type: GraphQLString },
        launch_success: { type: GraphQLBoolean },
        rocket: { type: RocketType }
    })
});

const LaunchType = new GraphQLObjectType({
    name: "Rocket",
    fields: () => ({
        rocket_id: { type: GraphQLString },
        rocket_name: { type: GraphQLString },
        rocket_type: { type: GraphQLString }
    })
});

Once you have the data model, we need to get data from a database or a third-party API, in which we get from spacex official API. We need to define a root query, root query as entrance for all queries, processing and returns the data, Please refer GraphQL Root Fields & Resolvers. .

The schema.jsincrease in the code:

const axios = require("axios");

const RootQuery = new GraphQLObjectType({
    name: "RootQueryType",
    fields: {
        launches: {
            type: new GraphQLList(LaunchType),
            resolve(parent, args) {
                return axios
                    .get("https://api.spacexdata.com/v3/launches")
                    .then(res => res.data);
            }
        }
    }
});

module.exports = new GraphQLSchema({
    query: RootQuery
});

Query List

This is done, the server api basically completed structures! We look at the results, enter in your browser to http: // localhost: 5000 / graphql opens Graphiql (production environment is recommended to disable):

We can only query of all flight_number:

Or more attributes:

Is not it simply amazing!

A single query

We can also query the information by passing a single parameter:

const RootQuery = new GraphQLObjectType({
    name: "RootQueryType",
    fields: {
        launch: {
            type: LaunchType,
            args: {
                flight_number: { type: GraphQLInt }
            },
            resolve(parent, args) {
                return axios
                    .get(
                        `https://api.spacexdata.com/v3/launches/${
                            args.flight_number
                        }`
                    )
                    .then(res => res.data);
            }
        }
    }
});

result:

It recommends the use Fundebug , a good use of monitoring tools - BUG

GraphQL front end

We are just using GraphiQL call interface in the browser, let's look at how to call graphql service at the front page. We use the front react.

Initialization react projects in the project root directory:

$ npx create-react-app client

To facilitate debugging in package.jsonincreased scripts:

"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev":"concurrently \"npm run server\" \"npm run client\" "

We use a style theme bootswatch in:

GraphQL的客户端有多种实现,本次项目使用 Apollo,最流行的GraphQL Client。更多client请参考 GraphQL Clients

安装依赖

安装如下依赖:

$ cd client
$ npm i apollo-boost react-apollo graphql

其中 apollo-boost 是apollo client本身,react-apollo 是react视图层的集成,graphql 用于解析graphql的查询语句。

设置client

修改App.js内容如下:

import React, { Component } from "react";
import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";
import "./theme.css";
import "./App.css";
import logo from "./spacex-logo-light.png";

const client = new ApolloClient({
    uri: "http://localhost:5000/graphql"
});

class App extends Component {
    render() {
        return (
            <ApolloProvider client={client}>
                <div className="container">
                    <img src={logo} id="logo" />
                </div>
            </ApolloProvider>
        );
    }
}

export default App;

和redux使用<Provider>传递store类似,react-apollo 通过 <ApolloProvider>将apollo client向下传递。

实现query

接着我们来实现显示launches的component,新增文件 components/Launches.js

import React, { Component, Fragment } from "react";
import gql from "graphql-tag";
import { Query } from "react-apollo";
import LaunchItem from "./LaunchItem";

const LAUNCHES_QUERY = gql`
    query LaunchesQuery {
        launches {
            flight_number
            mission_name
            launch_date_local
            launch_success
        }
    }
`;

export class Launches extends Component {
    render() {
        return (
            <Fragment>
                <h1 className="display-4 my-3">Launches</h1>
                <Query query={LAUNCHES_QUERY}>
                    {({ loading, error, data }) => {
                        if (loading) return <h4>Loading...</h4>;
                        if (error) console.log(error);
                        return (
                            <Fragment>
                                {data.launches.map(launch => (
                                    <LaunchItem
                                        key={launch.flight_number}
                                        launch={launch}
                                    />
                                ))}
                            </Fragment>
                        );
                    }}
                </Query>
            </Fragment>
        );
    }
}

export default Launches;

query语句通过 graphql-tag 定义,传入 <Query> 执行获取数据并传入 LaunchItem 显示。

components/LaunchItem.js:

import React from "react";

export default function LaunchItem({
    launch: { flight_number, mission_name, launch_date_local, launch_success }
}) {
    return (
        <div className="card card-body mb-3">
            <div className="col-md-9">
                <h4>Mission: {mission_name}</h4>
                <p>Date: {launch_date_local}</p>
            </div>
            <div className="col-md-3">
                <button className="btn btn-secondary">Launch Details</button>
            </div>
        </div>
    );
}

查询语句通过graphql-tag定义,然后传入<Query>执行。

运行

由于本地调试,client和server分别运行在不同的端口,所以需要先进行跨域处理,使用 cors

// server.js
const cors = require('cors');
app.use(cors());

效果

好了,大功告成,我们来看一下效果:

结语

今天就主要介绍GraphQL工程的搭建和GraphQL Query的使用,更多关于GraphQL的内容比如 Mutation下次有空会跟大家逐步讲解。

本文灵感来源:Youtube@Traversy Media,感谢

本文Demo Github地址:Github@MudOnTire

本文Demo线上展示:Heroku@graphql-spacex-launches

最后,推荐大家使用Fundebug,一款很好用的BUG监控工具~

关于Fundebug

Fundebug专注于JavaScript、微信小程序、微信小游戏、支付宝小程序、React Native、Node.js和Java线上应用实时BUG监控。 自从2016年双十一正式上线,Fundebug累计处理了10亿+错误事件,付费客户有阳光保险、核桃编程、荔枝FM、掌门1对1、微脉、青团社等众多品牌企业。欢迎大家免费试用!

Guess you like

Origin www.cnblogs.com/fundebug/p/quick-graphql-tutorial.html