🚀

ApolloでGraphQLやってみた

2022/01/30に公開

Apollo ServerとApollo Clientを利用して、GraphQLを試してみました

Server

公式チュートリアルのままです
https://www.apollographql.com/docs/apollo-server/getting-started/

apollo $ mkdir graphql-server-example
apollo $ cd graphql-server-example
graphql-server-example $ npm init --yes
graphql-server-example $ npm install apollo-server graphql
graphql-server-example $ touch index.js
index.js
const { ApolloServer, gql } = require("apollo-server");

const typeDefs = gql`
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

const books = [
  {
    title: "The Awakening",
    author: "Kate Chopin",
  },
  {
    title: "City of Glass",
    author: "Paul Auster",
  },
];

const resolvers = {
  Query: {
    books: () => books,
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
最終的な構成
graphql-server-example $ tree -a -I node_modules
.
├── index.js
├── package-lock.json
└── package.json

0 directories, 3 files
graphql-server-example $ node index.js
Server ready at http://localhost:4000/

Client

公式チュートリアルを参考にServerの情報を取得するように変更しました
https://www.apollographql.com/docs/react/get-started/

create-react-appで雛形作成

apollo$ npx create-react-app apollo-client
apollo$ cd apollo-client
apollo-client$ npm install @apollo/client graphql
index.js
import React from "react";
import ReactDOM from "react-dom";
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  useQuery,
  gql,
} from "@apollo/client";

const client = new ApolloClient({
  uri: "http://localhost:4000/",
  cache: new InMemoryCache(),
});

const booksQuery = gql`
  query ExampleQuery {
    books {
      title
      author
    }
  }
`;

function Books() {
  const { loading, error, data } = useQuery(booksQuery);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return data.books.map(({ title, author }) => (
    <div key={title}>
      <p>
        {title}: {author}
      </p>
    </div>
  ));
}

function App() {
  return (
    <div>
      <h2>My first Apollo app 🚀</h2>
      <Books />
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>,
  document.getElementById("root")
);
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

使用していないファイルを削除しました

最終的な構成
apollo-client $ tree -a -I "node_modules|.git" 
.
├── .gitignore
├── package-lock.json
├── package.json
├── public
│   └── index.html
└── src
    └── index.js

2 directories, 5 files
apollo-client $ npm start

http://localhost:3000

Discussion