GraphQL初学者的后端/前端示例代码

我突然想到,或许该加入GraphQL……但我发现在将其应用于繁琐系统时,意外地很麻烦,不知道从何入手,或者说,GraphQL到底是什么东西呢?所以我先准备了一个简单构建的示例,希望能帮到有类似困扰的人们。

顺便说一句,通过ChatGPT创建的基本方法是使用Express作为后端,React作为前端。它已经可以在Docker上运行。

※关于Docker化和各种微调,我已经自己完成了。

 

原文:コードの解説

中文翻译:代码解释

关于后端部分

后端框架基于Express。我们使用了Express的GraphQL插件。

要增加字段,需要分别修改 buildSchema 和 root 的内容。

GraphQL本身与此完全无关,但由于前端和后端运行的端口不同,因此需要在后端配置CORS以确保注意事项。

const express = require('express');
const cors = require('cors');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
const schema = buildSchema(`
  type Query {
    hello: String
    hello2: String
  }
`);

// The root provides a resolver function for each API endpoint
const root = {
  hello: () => 'Hello, GraphQL!',
  hello2: () => 'Hello2, GraphQL!',
};

const app = express();

app.use(cors());
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true, // Enable GraphiQL for testing the API in the browser
}));

app.listen(3000, () => {
  console.log('GraphQL server running at http://localhost:3000/graphql');
});

关于前端部分

前端基于React进行开发,作为GraphQL客户端选用了最知名的Apollo库。

在后端提供的模式中,有两个名为 hello 和 hello2 的字段,但前端只需要取得 hello 字段。

import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'http://localhost:3001/graphql', // Replace with your server URL
  cache: new InMemoryCache()
});

const GET_HELLO = gql`
  query {
    hello
  }
`;

function App() {
  const { loading, error, data } = useQuery(GET_HELLO);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>[Error] {error.toString()}</p>;

  return (
    <div>
      <h1>{data.hello}</h1>
    </div>
  );
}

function AppWrapper() {
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
}

export default AppWrapper;

补充:关于前端GraphQL客户端库

由于我只知道GraphQL客户端中的Apollo,所以开始有些不安,于是我做了一些调查,个人认为如果想跟上最新的流行趋势,至少可以先选择以下这个网站,那里也推荐了Apollo。因此,目前来看,Apollo仍然是最佳的初始选择,没有错的。

 

スクリーンショット 2023-07-11 22.52.24.png

顺便提一下,还有一个关于GraphQL的路线图。

 

在这个地方,一旦开始追逐,就没有尽头了呢…。

bannerAds