クエリ > アプリケーションからのクエリ

アプリケーションからのクエリ

Reading time: 6 min

サブグラフが Subgraph Studio または Graph Explorer にデプロイされると、GraphQL API のエンドポイントが与えられ、以下のような形になります。

Subgraph Studio (テスト用エンドポイント)

Queries (HTTP)
https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>

グラフエクスプローラ

Queries (HTTP)
https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>

GraphQL エンドポイントを使用すると、さまざまな GraphQL クライアントライブラリを使用してサブグラフをクエリし、サブグラフによってインデックス化されたデータをアプリに入力することができます。

ここでは、エコシステムで人気のある GraphQL クライアントをいくつか紹介し、その使い方を説明します:

GraphQL clients

このセクションへのリンク

The Graphは、独自のGraphQLクライアントgraph-clientを提供し、以下のような独自の機能をサポートしています:

  • クロスチェーンのサブグラフ処理:1回のクエリで複数のサブグラフからクエリを実行可能
  • 自動ブロック追跡
  • 自動ページング
  • 完全なタイプ付け結果

さらに、ApolloやURQLなどの人気のあるGraphQLクライアントと統合され、すべての環境(React、Angular、Node.js、React Native)と互換性があり、graph-clientを使用することで、The Graphとの対話の最良のエクスペリエンスが得られます。

以下は、graphql-clientを使用してサブグラフからデータを取得する方法を見てみましょう。

始める前に、プロジェクトにThe Graph Client CLIをインストールしてください。

yarn add -D @graphprotocol/client-cli
# or, with NPM:
npm install --save-dev @graphprotocol/client-cli

.graphql ファイルでクエリを定義します (または、.js または .ts ファイルにインラインで)。

query ExampleQuery {
# this one is coming from compound-v2
markets(first: 7) {
borrowRate
cash
collateralFactor
}
# this one is coming from uniswap-v2
pair(id: "0x00004ee988665cdda9a1080d5792cecd16dc1220") {
id
token0 {
id
symbol
name
}
token1 {
id
symbol
name
}
}
}

次に、設定ファイル(.graphclientrc.ymlと呼ばれる)を作成し、The Graphが提供するGraphQLエンドポイントを指定します。例えば:

# .graphclientrc.yml
sources:
- name: uniswapv2
handler:
graphql:
endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2
- name: compoundv2
handler:
graphql:
endpoint: https://api.thegraph.com/subgraphs/name/graphprotocol/compound-v2
documents:
- ./src/example-query.graphql

以下のThe Graph Client CLIコマンドを実行すると、型付けされたJavaScriptコードが生成され、すぐに使用できる状態になります。

graphclient build

最後に、生成された型付きのGraphQLドキュメントを使用するために、.tsファイルを更新してください。

import React, { useEffect } from 'react'
// ...
// we import types and typed-graphql document from the generated code (`..graphclient/`)
import { ExampleQueryDocument, ExampleQueryQuery, execute } from '../.graphclient'
function App() {
const [data, setData] = React.useState<ExampleQueryQuery>()
useEffect(() => {
execute(ExampleQueryDocument, {}).then((result) => {
setData(result?.data)
})
}, [setData])
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Graph Client Example</p>
<fieldset>
{data && (
<form>
<label>Data</label>
<br />
<textarea value={JSON.stringify(data, null, 2)} readOnly rows={25} />
</form>
)}
</fieldset>
</header>
</div>
)
}
export default App

⚠️ 重要なお知らせ

graph-clientは、Apolloクライアント、URQL、React Queryなどの他のGraphQLクライアントと完全に統合されています。公式リポジトリには例があります

ただし、別のクライアントを選択する場合は、クロスチェーンサブグラフ処理や自動ページネーションといった、The Graphのクエリングの中核的な機能を利用できないことに注意してください。

Apollo クライアント

このセクションへのリンク

Apollo Clientは、フロントエンドエコシステムで広く使われているGraphQLクライアントです。

React、Angular、Vue、Ember、iOS、およびAndroid向けに利用可能なApollo Clientは、最も重いクライアントですが、GraphQLを基にした高度なUIを構築するための多くの機能を提供します。

  • 高度なエラー処理
  • ページネーション
  • データのプリフェッチ
  • 楽観的な UI
  • ローカル状態管理

Apollo Clientを使用してウェブプロジェクトでサブグラフからデータを取得する方法を見てみましょう。

First, install @apollo/client and graphql:

npm install @apollo/client graphql

その後、以下のコードで API をクエリできます:

import { ApolloClient, InMemoryCache, gql } from '@apollo/client'
const APIURL = 'https://api.studio.thegraph.com/query//<SUBGRAPH_NAME>/'
const tokensQuery = `
query {
tokens {
id
tokenID
contentURI
metadataURI
}
}
`
const client = new ApolloClient({
uri: APIURL,
cache: new InMemoryCache(),
})
client
.query({
query: gql(tokensQuery),
})
.then((data) => console.log('Subgraph data: ', data))
.catch((err) => {
console.log('Error fetching data: ', err)
})

変数を使用するには、クエリにvariables引数を渡すことができます:

const tokensQuery = `
query($first: Int, $orderBy: BigInt, $orderDirection: String) {
tokens(
first: $first, orderBy: $orderBy, orderDirection: $orderDirection
) {
id
tokenID
contentURI
metadataURI
}
}
`
client
.query({
query: gql(tokensQuery),
variables: {
first: 10,
orderBy: 'createdAtTimestamp',
orderDirection: 'desc',
},
})
.then((data) => console.log('Subgraph data: ', data))
.catch((err) => {
console.log('Error fetching data: ', err)
})

もう一つの選択肢はURQLで、Node.js、React/Preact、Vue、およびSvelteの環境で利用でき、より高度な機能が備わっています。

  • 柔軟なキャッシュ システム
  • Extensible design(新しい機能の追加を容易にする)
  • Lightweight bundle(Apollo Clientの約5倍の軽さ)
  • ファイルアップロードとオフラインモードに対応

URQLを使用してウェブプロジェクトでサブグラフからデータを取得する方法を見てみましょう。

まず、urqlgraphqlをインストールします:

npm install urql graphql

その後、以下のコードで API をクエリできます:

import { createClient } from 'urql'
const APIURL = 'https://api.thegraph.com/subgraphs/name/username/subgraphname'
const tokensQuery = `
query {
tokens {
id
tokenID
contentURI
metadataURI
}
}
`
const client = createClient({
url: APIURL,
})
const data = await client.query(tokensQuery).toPromise()
ページを編集

クエリのベストプラクティス
分散システム
ページを編集