subgraphs > Querying > 从应用程序中进行查询

从应用程序中进行查询

Reading time: 5 min

Learn how to query The Graph from your application.

Getting GraphQL Endpoint

链到本节

Once a subgraph is deployed to Subgraph Studio or Graph Explorer, you will be given the endpoint for your GraphQL API that should look something like this:

子图工作室

链到本节
https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>

Graph浏览器

链到本节
https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>

With your GraphQL endpoint, you can use various GraphQL Client libraries to query the subgraph and populate your app with data indexed by the subgraph.

Graph Client

链到本节

The Graph is providing its own GraphQL client, graph-client that supports unique features such as:

  • 跨链子图处理: 在一个查询中从多个子图进行查询
  • 自动区块追踪
  • 自动分页
  • 完全类型化的结果

Note: graph-client is integrated with other popular GraphQL clients such as Apollo and URQL, which are compatible with environments such as React, Angular, Node.js, and React Native. As a result, using graph-client will provide you with an enhanced experience for working with The Graph.

Fetch Data with Graph Client

链到本节

Let's look at how to fetch data from a subgraph with graph-client:

步骤1

链到本节

Install The Graph Client CLI in your project:

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

步骤2

链到本节

.graphql 文件中定义查询(或在.js or .ts文件中内联):

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

步骤3

链到本节

Create a configuration file (called .graphclientrc.yml) and point to your GraphQL endpoints provided by The Graph, for example:

# .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

Step 4

链到本节

Run the following The Graph Client CLI command to generate typed and ready to use JavaScript code:

graphclient build

Step 5

链到本节

Update your .ts file to use the generated typed GraphQL documents:

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

Important Note: graph-client is perfectly integrated with other GraphQL clients such as Apollo client, URQL, or React Query; you can find examples in the official repository. However, if you choose to go with another client, keep in mind that you won't be able to use Cross-chain Subgraph Handling or Automatic Pagination, which are core features for querying The Graph.

Apollo Client

链到本节

Apollo client is a common GraphQL client on front-end ecosystems. It's available for React, Angular, Vue, Ember, iOS, and Android.

Although it's the heaviest client, it has many features to build advanced UI on top of GraphQL:

  • Advanced error handling
  • 分页
  • Data prefetching
  • Optimistic UI
  • Local state management

Fetch Data with Apollo Client

链到本节

Let's look at how to fetch data from a subgraph with Apollo client:

步骤1

链到本节

Install @apollo/client and graphql:

npm install @apollo/client graphql

步骤2

链到本节

Query the API with the following code:

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)
})

步骤3

链到本节

要使用变量,你可以在查询中传递一个变量参数

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 Overview

链到本节

URQL is available within Node.js, React/Preact, Vue, and Svelte environments, with some more advanced features:

  • 灵活的缓存系统
  • 可扩展设计(使在它上面添加新功能变得容易)
  • 轻量级捆绑包(比 Apollo Client 小约5倍)
  • 支持文件上传和离线模式

Fetch data with URQL

链到本节

Let's look at how to fetch data from a subgraph with URQL:

步骤1

链到本节

Install urql and graphql:

npm install urql graphql

步骤2

链到本节

Query the API with the following code:

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()
编辑

上页
查询最佳实践
下页
分布式系统
编辑