GraphQL entry details

  api, express, graphql, node.js, react.js

brief introduction

Definition

A Data Query Language for API Calls

Core idea

The traditional api call usually obtains a complete object assembled by the back end, but the front end may only need to use some fields, and most of the data query and transmission work is wasted. GraphQL provides a brand-new data query method, which can only obtain the required data, making api calls more flexible, efficient and low-cost.

Characteristics

  1. Get whatever data you need.
  2. Support query of relational data
  3. The API does not need to define various routes, and is completely data-driven
  4. There is no need to manage API versions, and one version continues to evolve.
  5. Support most mainstream development languages and platforms
  6. Powerful supporting development tools

Use method

Let’s build oneSpaceXTo intuitively learn the basic usage of graphQLOfficial apisGet.

Server side

Node+express is adopted for the server. Create a new node project and install the following dependencies:

$ npm i graphql express-graphql express axios

Create entry fileserver.js, which creates express services. With graphQL, we only need to set up a route, and all requests are handled by this graphQL’s request handler:

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 the http service of grapql, which is used to process query requests of grapql. it receives an options parameter, where schema is anGraphQLSchemaAs an example, let’s define that graphQL can be directly debugged in the browser when graphql is set to true. For more usage of express-graphql, please refer toGithub express-graphql.

schema

Next, we define schema, which means’ schema’, which defines the structure of the data model, the types of fields, and the relationships between models, and is the core of graphQL.

Newschema.jsFile, first define two data models: LaunchType and RocketType. Note that the data type of the field needs to be defined by GraphQL, and the basic data type in js cannot be used.

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 }
 })
 });

After having the data model, we need to obtain the data from the database or the third party API, and here we obtain the data from spacex’s official API. We need to define a root query as the entry for all queries, to process and return data, please refer toGraphQL Root fields & resolvers.

Inschema.jsAdd code to:

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

To complete this step, the server-side api is basically set up! Let’s look at the effect and enter it in the browser.http://localhost:5000/graphqlGraphiql will be opened (recommended for production environment):

image

We can only query allflight_number

image

Or more attributes:

image

Is it very simple and amazing?

Single query

We can also query a single piece of information by passing in parameters:

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);
 }
 }
 }
 });

Results:

image

Front end

Just now, we all use graphql to call the interface in the browser. Next, let’s look at how to call GraphQL service in the front page. We use react at the front end.

Initialize react project in project root directory:

$ npx create-react-app client

In order to facilitate debugging, inpackage.jsonAdd scripts to:

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

Style We use a theme from bootswatch:

image

GraphQL has a variety of client implementations, which are used in this project.Apollo, the most popular GraphQL Client. For more client, please refer toGraphQL Clients.

Installation dependency

Install the following dependencies:

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

among themapollo-boostApollo client itself,react-apolloIt is the integration of react view layer.graphqlQuery statement used to parse graphql.

Set client

ModifyApp.jsThe content is as follows:

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;

And redux<Provider>The delivery store is similar.react-apollovia<ApolloProvider>Pass apollo client down.

Implement query

Next, let’s implement the component that displays launches and add files.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 statement passedgraphql-tagDefinition, incoming<Query>Perform data acquisition and pass inLaunchItemShow.

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>
)
}

Query statement passedgraphql-tagDefinition, and then passed in<Query>Execute.

run

Because of local debugging, client and server are running on different ports respectively, so cross-domain processing is required first, and thecors.

server.js

const cors = require('cors');
 
 ...
 
 app.use(cors());

Effect

Well, it’s done, let’s look at the effect:

image

Conclusion

Today, I will mainly introduce the construction of GraphQL project and the use of GraphQL Query. more about GraphQL includeMutationI will explain it step by step with you next time when I am free.

The inspiration for this article is:Youtube@Traversy MediaThank you

This article Demo Github address:Github@MudOnTire

This article Demo online shows:Heroku@graphql-spacex-launches