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

从应用程序中进行查询

一旦子图被部署到子图工作室或 Graph浏览器,你将得到 GraphQL API 的端点,它应该看起来像这样:

子图工作室(测试端点)

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

Graph浏览器

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

使用 GraphQL 端点,你可以使用各种 GraphQL 客户端库来查询子图,并用子图索引的数据来填充你的应用程序。

下面是生态系统中几个比较流行的 GraphQL 客户端以及如何使用它们。

GraphQL客户端

链到本节

Graph 客户端

链到本节

Graph提供了自己的GraphQL客户端,graph-client支持以下独特功能:

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

还与流行的GraphQL客户端(如Apollo和URQL)集成,并与所有环境(React、Angular、Node.js、React Native)兼容,使用graph-client将为您提供与Graph交互的最佳体验。

让我们看看如何使用 graphql-client 从子图获取数据。

首先,请确保在项目中安装 Graph Client CLI:

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

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

然后,创建一个配置文件(名为. grapclientrc.yml)并指向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

运行以下 Graph Client CLI 命令将生成类型化的并可以投入使用 的JavaScript 代码:

graphclient build

最后,更新.ts 文件以使用生成的类型化 GraphQL 文档:

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 与其他 GraphQL 客户端(如 Apollo client、 URQL 或 React Query)完美地集成; 您可以在正式存储库中找到示例

但是,如果您选择使用另一个客户端,请记住您将无法使用跨链子图处理或自动分页,这是查询Graph 的核心功能

Apollo 客户端

链到本节

Apollo 客户端是前端生态系统中无处不在的 GraphQL 客户端。

Apollo Client可用于React、Angular、Vue、Ember、iOS和Android,虽然是重量级的客户端,但它在GraphQL之上提供了许多构建高级UI的功能:

  • 高级错误处理
  • 分页
  • 数据预取
  • 优化用户界面
  • 本地状态管理

让我们看看如何在一个web项目中用 Apollo 客户端从子图中获取数据。

首先,安装@apollo/clientgraphql:

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

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

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 环境中使用,具有更高级的特性:

  • 灵活的缓存系统
  • 可扩展设计(使在它上面添加新功能变得容易)
  • 轻量级捆绑包(比 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()
编辑

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