6章-2 Apollo Client の実装 / 翻訳
TweetRepresentational State Transfer(REST)を使用することの大きなメリットは、キャッシュの処理が容易であることです。REST を使用すると、request を実行して返ってきた response データを、その request にアクセスするために使用された URL 元でキャッシュとして保存できます。キャッシュするだけ。問題ありません。しかし、GraphQL の caching は少し面倒です。 GraphQL の場合、エンドポイントが複数あるわけではありません。つまりすべてが単一のエンドポイントで送受信されますので、あるエンドポイントから返されたデータをその URL の元で保存することができません。
A huge benefit of using Representational State Transfer (REST) is the ease with which you can handle caching. With REST, you can save the response data from a request in a cache under the URL that was used to access that request. Caching done, no problem. Caching GraphQL is a little trickier. We don’t have a multitude of routes with a GraphQL API— everything is sent and received over a single endpoint, so we cannot simply save the data returned from a route under the URL that was used to request it.
To build a robust, performant application, we need a way to cache queries and their resulting objects. Having a localized caching solution is essential as we constantly strive to create fast, efficient apps. We could create something like this ourselves, or we could lean on one of the vetted clients that already exist.
The most prominent GraphQL client solutions available today are Relay and Apollo Client. Relay was open sourced by Facebook in 2015 at the same time as GraphQL. It brings together everything that Facebook learned about using GraphQL in production. Relay is compatible with React and React Native only, which means that there was an opportunity to create a GraphQL client to support developers who might not use React.
Enter Apollo Client. Brought to you by Meteor Development Group, Apollo Client is a community-driven project to build a flexible GraphQL client solution to handle tasks like caching, optimistic UI updates, and more. The team has created packages that supply bindings for React, Angular, Ember, Vue, iOS, and Android.
We’ve already been using several tools from the Apollo team on the server, but Apollo Client focuses specifically on sending and receiving requests from the client to the server. It handles the network requests with Apollo Link and handles all caching with Apollo Cache. Apollo Client then wraps the link and the cache and manages all interactions with the GraphQL service efficiently.
For the rest of the chapter, we take a closer look at Apollo Client. We’re going to be using React to build out our UI components, but we can apply many of the techniques described here to projects that use different libraries and frameworks.
Apollo Client with React
Since working with React is what led us to GraphQL in the first place, we have chosen React as the user interface library. We haven’t offered much explanation about React itself. It is a library that was created at Facebook that uses a component-based architecture to compose UIs. If you are a user of a different library and you never want to look at React again after this, that’s ok. The ideas presented in this next section are applicable to other UI frameworks.
Project Setup
この章では、Apollo Client を用いた、GraphQL サービスと interact する React アプリケーションを構築する方法を説明していきます。まずは create-react-app を使用してプロジェクトのフロントエンドの雛形を作成していきます。create-react-app は様々な設定をしなくても、React プロジェクトを作成することができるツールです。create-react-app を一度も使用したことがない場合には、まずはインストールをしましょう。
yarn global add create-react-app
In this chapter, we show you how to build a React app that interacts with a GraphQL service using Apollo Client. To begin, we need to scaffold the frontend of this project using create-react-app. create-react-app allows you to generate an entire React project without setting up any build configuration. If you haven’t used create-react-app before, you might need to install it:
インストールされたら、以下のコマンドをどこでも実行でき、それによって React プロジェクトを作成することができます。
create-react-app photo-share-client
Once installed, you can create a React project anywhere on your computer with:
このコマンドは React アプリケーションのベースとなる部分を新しく作成して、photo-share-client
フォルダーにインストールしてくれます。React app を作成するにあたって必要なものを全てインストールします。アプリケーションを起動するためには、photo-share-client
フォルダに移動して run npm start
を実行します。するとブラウザが自動で開かれて http://localhost:3000
で React のクライアントアプリケーションが起動したことを確認できます。繰り返しになりますが、このチャプターの全ての参考ファイルは、http://github.com/moonhighway/learning-graphql
リポジトリにありますので、適宜確認してください。
This command installs a new base React application in a folder named photo-share-client. It automatically adds and installs everything that you will need to get started building a React app. To start the application, navigate to the photo-share-client folder and run npm start. You’ll see your browser open to http://localhost:3000 where your React client application is running. Remember, you can find all of the files for this chapter in the repository at
http://github.com/moonhighway/learning-graphql
.
Configure Apollo Client
GraphQL client を Apollo を使って開発するために、いくつか必要なパッケージをインストールしていきます。まずは graphql が必要ですね。これには GraphQL language parser が含まれています。次に apollo-boost が必要です。Apollo Boost に含まれるのは、Apollo Client を作るために必要なパッケージと、それから operation を Apollo Client へ送るために必要なパッケージが含まれています。最後に react-apollo が必要です。React Apollo には React Component が含まれていて、このコンポーネントを使って Apollo のユーザーインターフェイスを構築していきます。
You’ll need to install a few packages to build a GraphQL client with Apollo tools. First, you’ll need graphql which includes the GraphQL language parser. Then you’ll need a package called apollo-boost. Apollo Boost includes the Apollo packages necessary for creating an Apollo Client and sending operations to that client. Finally, we’ll need react-apollo. React Apollo is an npm library that contains React components that we will use to construct a user interface with Apollo.
ではこれら三つのパッケージをインストールしましょう。
Let’s install these three packages at the same time:
yarn add graphql apollo-boost react-apollo
Now we are ready to create our client. The ApolloClient constructor found in apollo-boost can be used to create our first client. Open the src/index.js file and replace the code in that file with the following:
import ApolloClient from 'apollo-boost' const client = new ApolloClient({ uri: 'http://localhost:4000/graphql' })
import ApolloClient, { gql } from 'apollo-boost'
const client = new ApolloClient({ uri: 'http://localhost:4000/graphql' })
const query = gql{
totalUsers
totalPhotos
}
client
.query({ query })
.then(({ data }) => console.log(' data', data))
.catch(console.error)
import React from 'react' import { render } from 'react-dom' import './index.css' import App from './App' import * as serviceWorker from './serviceWorker'
import { ApolloProvider } from 'react-apollo' import ApolloClient from 'apollo-boost' const client = new ApolloClient({ uri: '/graphql' })
render(