react中GraphQL的简单应用

express服务端实现GraphQL

  1. 创建node项目 安装graphQL相关库

    mkdir node_server
    cd node_server
    npm init -y
    yarn add graphql express-graphql express axios
    
  2. 创建入口文件server.js
    在server.js中创建express服务。使用graphQL中设置一个路由,所有的请求都由这个graphQL的这个路由处理:

    const express = require("express");
     const { graphqlHTTP } = require("express-graphql");
     const schema = require("./schema");         //引入schema
     const cors = require("cors");                     //解决跨域
    
     const app = express();
     app.use(cors());
     app.use("/graphql",graphqlHTTP({
         schema,
         graphiql: true,
     })
     );
     const PORT = process.env.PORT || 5000;
     app.listen(PORT, () => console.log(`服务器运行在${PORT}端口上`));
    
  3. 新建schema文件

    schema意为'模式',其中定义了数据模型的结构,字段的类型,模型间的关系,是graphQL的核心。
    新建schema.js文件,首先定义两个数据模型,LaunchType(发射)和RocketType(火箭)。注意字段的数据类型需要使用GraphQL定义的,不能使用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_date_local: { type: GraphQLString },
        launch_year: { 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) => {
                console.log("访问---")
                return res.data;
            });
        },
        },
    },
    });
    
    module.exports = new GraphQLSchema({
    query: RootQuery,
    });
    
    
    // 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);
    //           }
    //       }
    //   }
    // });
    
    //单个查询的graphQL命令
    //launch(flight_number:2){
       // mission_name,
        //launch_year,
        //launch_success,
      //  rocket{
         //   rocket_name,
       //     rocket_type
        }
    //}
    
  4. 查询列表

    启动server.js,访问http://localhost:5000/graphql,输入:

    {
        launches{
            mission_name,
            launch_year,
            launch_success
        }
    }
    

    成功得到远端数据。

  5. 新建客户端

    新建react的客户端项目 yarn create vite graph_ql_client --template react 然后安装@apollo/client

    yarn add @apollo/client
    
  6. 更改main.jsx 成如下内容

    import React from "react";
    import ReactDOM from "react-dom/client";
    import App from "./App";
    import "./index.css";
    import {
        ApolloClient,
        InMemoryCache,
        ApolloProvider,
        gql,
    } from "@apollo/client";
    
    const client = new ApolloClient({
        uri: "http://localhost:5000/graphql/",
        cache: new InMemoryCache(),
    });
    
    ReactDOM.createRoot(document.getElementById("root")).render(
    <React.StrictMode>
        <ApolloProvider client={client}>
            <App />
        </ApolloProvider>
    </React.StrictMode>
    );
    
  7. 更改App.js成内容:

    import "./App.css";
    import { useQuery, gql } from "@apollo/client";
    import LaunchItem from "./components/LaunchItem.jsx";
    import style from './assets/style.module.css'
    
    const GET_DATA = gql`
    {
        launches {
        mission_name
        launch_year
        launch_success
        }
    }
    `;
    
    function App() {
    const { loading, error, data } = useQuery(GET_DATA);
    
    if (loading) return <div>loading</div>;
    if (error) return <div>error</div>;
    console.log("data---",data)
    
    return (
        <div className="App">
        <div className={style.box}>
            {data
            ? data.launches.map((item) => (
                <LaunchItem
                    name={item.mission_name}
                    year={item.launch_year}
                    success={item.launch_success}
                />
                ))
            : null}
        </div>
        </div>
    );
    }
    
    export default App;
    
  8. 创建LaunchItem.jsx

    import React from 'react'
    import style from '../assets/style.module.css'
    
    function LaunchItem({name,year,success,rocketName}) {
    return (
        <div className={style.item} style={{backgroundColor:success?'green':'gray'}}>
            <div>名字:{name}</div>
            <div>生产日期:{year}</div>
            <div>是否成功:{success?"成功":"失败"}</div>
        </div>
    )
    }
    
    export default LaunchItem
    

本文作者:sy0313

本文链接:https://www.cnblogs.com/sunyan97/p/16866264.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   sy0313  阅读(38)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起