剧场模式
首页前后端分离GraphQLGraphQL + React + React Router + Apollo 实战教程

GraphQL + React + React Router + Apollo 实战教程 #3 使用 axios 发送请求跑起来获得数据

海外散仙厉飞雨 · 真仙发布于
0

源码:https://github.com/hfpp2012/hello-apollo

https://github.com/prisma/graphql-playground/releases

schema.js

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

const axios = require('axios');

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

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

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

server.js

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 || 4000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
0 条回复
暂无回复~~

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 在线学员:102

Top