Graphql-apollo-client
GraphQL-Apolloクライアント
Apolloサーバーを使用して、サーバー側でgraphql仕様を作成しました。 実稼働対応のGraphQLサーバーをすばやく簡単に構築できます。 次に、クライアント側について理解しましょう。
Apollo Clientは、GraphQLを使用してクライアントアプリケーションを構築する最良の方法です。 クライアントは、開発者がGraphQLでデータを取得するUIを迅速に構築し、JavaScriptフロントエンドで使用できるように設計されています。
Apollo Clientは以下のプラットフォームをサポートしています-
Sr.No. | Platform & Framework |
---|---|
1 |
Javascript React、Angular、Vue、Meteor、Ember |
2 |
WebComponents ポリマー、lit-apollo |
3 |
Native Mobile Javaを備えたネイティブAndroid、Swiftを備えたネイティブiOS |
キャッシングは、Apolloクライアントの主要な機能の1つです。 apollo-boostは、他の多くの依存関係をもたらす便利なパッケージです。
図
私たちは次の手順を使用してクライアントアプリケーションを構築するためにApolloクライアントを使用する方法を見てみましょう-
サーバーのセットアップ
私たちは、サーバーをセットアップするために以下の手順に従う必要があります-
ステップ1-プロジェクトに必要な依存関係をダウンロードしてインストールする
フォルダapollo-server-appを作成します。 ターミナルからディレクトリを「 apollo-server-app 」に変更します。 次に、環境設定の章で説明されている手順3〜5を実行します。
ステップ2-スキーマを作成する
プロジェクトフォルダma apollo-server-app に schema.graphql ファイルを追加し、次のコードを追加します-
type Query
{
students:[Student]
}
type Student {
id:ID!
firstName:String
lastName:String
college:College
}
type College {
id:ID!
name:String
location:String
rating:Float
}
ステップ3-リゾルバーを追加する
プロジェクトフォルダにファイル resolvers.js を作成し、次のコードを追加します-
const db = require('./db')
const Query = {
//resolver function for students returns list
students:() => db.students.list(),
}
const Student = {
college:(root) => {
return db.colleges.get(root.collegeId);
}
}
module.exports = {Query,Student}
ステップ4-アプリケーションを実行する
*server.js* ファイルを作成します。 環境設定の章の手順8を参照してください。 ターミナルでコマンド_npm start_を実行します。 サーバーは9000ポートで稼働します。 ここでは、GraphiQLをクライアントとして使用して、アプリケーションをテストします。
ブラウザを開き、URL http://localhost:9000/graphiql を入力します。 エディターに次のクエリを入力します。
{
students{
id
firstName
college{
name
}
}
}
クエリの応答は以下のとおりです-
{
"data": {
"students": [
{
"id": "S1001",
"firstName": "Mohtashim",
"college": {
"name": "CUSAT"
}
},
{
"id": "S1002",
"firstName": "Kannan",
"college": {
"name": "AMU"
}
},
{
"id": "S1003",
"firstName": "Kiran",
"college": {
"name": "AMU"
}
}
]
}
}
クライアントのセットアップ
クライアント用の新しいターミナルを開きます。 サーバーアプリケーションは、クライアントアプリケーションを実行する前に実行し続ける必要があります。 Reactアプリケーションはポート番号3000で実行され、サーバーアプリケーションはポート番号9000で実行されます。
ステップ1-Reactアプリケーションを作成する
クライアント端末で、次のコマンドを入力します-
npx create-react-app hello-world-client
これにより、典型的なリアクションアプリケーションに必要なすべてがインストールされます。 npxユーティリティとcreate-react-appツールは、 hello-world-client という名前のプロジェクトを作成します。 インストールが完了したら、VSCodeでプロジェクトを開きます。
ステップ2-hello-world-clientを開始します
ターミナルの現在のフォルダーパスを hello-world-client に変更します。 npm startと入力して、プロジェクトを起動します。 これにより、ポート3000で開発サーバーが実行され、ブラウザーが自動的に開き、インデックスページが読み込まれます。
これは、以下のスクリーンショットに示されています-
ステップ3-Apolloクライアントライブラリのインストール
Apolloクライアントをインストールするには、新しいターミナルを開き、現在のプロジェクトフォルダーパスに移動します。 次のコマンドを入力します-
npm install apollo-boost graphql
これにより、クライアント側のgraphqlライブラリとApollo Boostパッケージがダウンロードされます。 これをクロスチェックするには、apollo-boost依存関係にinnpm viewと入力します。 以下に示すように、これには多くの依存関係があります-
{
'apollo-cache': '^1.1.15',
'apollo-cache-inmemory': '^1.2.8',
'apollo-client': '^2.4.0',
'apollo-link': '^1.0.6',
'apollo-link-error': '^1.0.3',
'apollo-link-http': '^1.3.1',
'apollo-link-state': '^0.4.0',
'graphql-tag': '^2.4.2'
}
Apollo-Clientライブラリがインストールされていることがはっきりとわかります。
手順4-index.jsファイルでアプリコンポーネントを変更する
Apollo Clientを使用すると、フェッチAPIを使用せずにサーバーを直接呼び出すことができます。 また、逆ティック表記で作成された文字列にクエリと突然変異を埋め込まないでください。 これは、 gql 関数がクエリを直接解析するためです。 つまり、プログラマはGraphiQLツールでクエリを作成するときと同じ方法でクエリを直接作成できます。 gql は、back tick表記で書かれたテンプレート文字列をgraphqlクエリオブジェクトに解析するタグ関数です。 Apolloクライアントクエリメソッドはプロミスを返します。
次のコードスニペットは、Apolloクライアントをインポートする方法を示しています-
import {ApolloClient, HttpLink, InMemoryCache} from 'apollo-boost'
const endPointUrl = 'http://localhost:9000/graphql'
const client = new ApolloClient({
link: new HttpLink({uri:endPointUrl}),
cache:new InMemoryCache()
});
前の章では、HTTPリクエストにフェッチAPIを使用する方法について説明しました。 次のコードは、 gql 関数の使用方法を示しています。 loadStudentsAsync 関数は、graphqlクライアントを使用してサーバーに照会します。
async function loadStudentsAsync() {
const query = gql`
{
students{
id
firstName
lastName
college{
name
}
}
}`
const {data} = await client.query({query}) ;
return data.students;
}
*index.js* を *src* フォルダーに保持し、indexlをパブリックフォルダーに保持するだけです。自動生成される他のすべてのファイルは削除できます。
ディレクトリ構造は以下のとおりです-
hello-world-client/
-->node_modules
-->public
indexl
-->src
index.js
-->package.json
以下は、reactアプリケーションの index.js です-
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
//apollo client
import {ApolloClient, HttpLink, InMemoryCache} from 'apollo-boost'
import gql from 'graphql-tag'
const endPointUrl = 'http://localhost:9000/graphql'
const client = new ApolloClient({
link: new HttpLink({uri:endPointUrl}),
cache:new InMemoryCache()
});
async function loadStudentsAsync() {
const query = gql`
{
students{
id
firstName
lastName
college{
name
}
}
}
`
const {data} = await client.query({query}) ;
return data.students;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
students:[]
}
this.studentTemplate = [];
}
async loadStudents() {
const studentData = await loadStudentsAsync();
this.setState({
students: studentData
})
console.log("loadStudents")
}
render() {
return(
<div>
<input type = "button" value = "loadStudents" onClick = {this.loadStudents.bind(this)}/>
<div>
<br/>
<hr/>
<table border = "3">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>college Name</td>
</tr>
</thead>
<tbody>
{
this.state.students.map(s => {
return (
<tr key = {s.id}>
<td>
{s.firstName}
</td>
<td>
{s.lastName}
</td>
<td>
{s.college.name}
</td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
次に示すように、loadStudentsボタンをクリックすると、反応アプリケーションはGraphQLサーバーから生徒をロードします-