Docs
搜索⌘ K
  • 主页
  • 关于 The Graph
  • 支持的网络
  • 协议合约
  • 子图
    • 子流
      • 代币 API
        • AI Suite
          • 索引
            • 资源
              子图 > 查询

              6 分钟

              从应用程序中进行查询

              学习如何从您的应用程序查询The Graph。

              获取GraphQL端点

              在开发过程中,您将在两个不同阶段收到一个 GraphQL API 端点:用于在Subgrah Studio进行测试和另一个在生产中查询The Graph网络的问题。

              子图工作室端点

              将Subgraph部署到Subgraph Studio后,您将收到一个如下所示的端点:

              1https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>

              此端点仅用于测试目的仅并且是限定频率。

              The Graph网络端点

              在将您的子图发布到网络后,您将收到一个看起来像这样的端点:

              1https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>

              此端点用于网络上的活动用途。 它允许您使用各种GraphQL客户端库查询子图并使用索引数据填充您的应用程序。

              使用热门GraphQL客户端

              Graph 客户端

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

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

              注意:graph-client 是与其他受欢迎的GraphQL客户端集成的,例如Apollo和 URQL,这些客户端与React、Angular、Node.js和React Native等环境兼容。 因此,使用 graph-client 可以为你提供与The Graph的更高工作体验。

              使用 Graph客户端获取数据

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

              步骤1

              在您的项目中安装The Graph客户端 CLI :

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

              步骤2

              定义在.graphql 文件(或在 .js 或 .ts 中嵌入)中的查询:

              1query ExampleQuery {2  # this one is coming from compound-v23  markets(first: 7) {4    borrowRate5    cash6    collateralFactor7  }8  #来自uniswap-v2的查询9  pair(id: "0x00004ee988665cdda9a1080d5792cecd16dc1220") {10    id11    token0 {12      id13      symbol14      name15    }16    token1 {17      id18      symbol19      name20    }21  }22}

              步骤3

              创建一个配置文件 (名为 .graphclientrc.yml) 并指向您的由The Graph提供的GraphQL 端点, 例如:

              1# .graphclientrc.yml2sources:3  - name: uniswapv24    handler:5      graphql:6        endpoint: https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>7  - name: compoundv28    handler:9      graphql:10        endpoint: https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>1112documents:13  - ./src/example-query.graphql

              步骤4

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

              1graphclient build

              步骤5

              更新您的 .ts 文件以使用生成的 GraphQL 文档:

              1import React, { useEffect } from 'react'2// ...3// we import types and typed-graphql document from the generated code (`..graphclient/`)4import { ExampleQueryDocument, ExampleQueryQuery, execute } from '../.graphclient'56function App() {7  const [data, setData] = React.useState<ExampleQueryQuery>()89  useEffect(() => {10    execute(ExampleQueryDocument, {}).then((result) => {11      setData(result?.data)12    })13  }, [setData])14  return (15    <div className="App">16      <header className="App-header">17        <img src={logo} className="App-logo" alt="logo" />18        <p>Graph Client Example</p>19        <fieldset>20          {data && (21            <form>22              <label>Data</label>23              <br />24              <textarea value={JSON.stringify(data, null, 2)} readOnly rows={25} />25            </form>26          )}27        </fieldset>28      </header>29    </div>30  )31}3233export default App

              重要注意: graph-client 与其他GraphQL客户端,如Apollo客户端、URL或React查询完全整合; 您可以在官方仓库中找到示例⁠。 然而,如果您选择与另一个客户端联系,请记住您将无法使用跨链子处理或自动分页, 它们是查询The Graph的核心功能。

              Apollo 客户端

              Apollo 客户端⁠ 是前端生态系统常见的 GraphQL 客户端。它可用于React、Angular、Vue、Ember、iOS和Android。

              虽然它是最重的客户端,但它有许多功能可以在 GraphQL 顶部构建高级用户界面:

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

              通过 Apollo 客户端获取数据

              让我们看看如何用 Apollo 客户端从子图中获取数据。

              步骤1

              安装 @apollo/client 和 graphql:

              1npm install @apollo/client graphql

              步骤2

              用以下代码查询API:

              1import { ApolloClient, InMemoryCache, gql } from '@apollo/client'23const APIURL = 'https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>'45const tokensQuery = `6  query {7    tokens {8      id9      tokenID10      contentURI11      metadataURI12    }13  }14`1516const client = new ApolloClient({17  uri: APIURL,18  cache: new InMemoryCache(),19})2021client22  .query({23    query: gql(tokensQuery),24  })25  .then((data) => console.log('Subgraph data: ', data))26  .catch((err) => {27    console.log('Error fetching data: ', err)28  })

              步骤3

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

              1const tokensQuery = `2  query($first: Int, $orderBy: BigInt, $orderDirection: String) {3    tokens(4      first: $first, orderBy: $orderBy, orderDirection: $orderDirection5    ) {6      id7      tokenID8      contentURI9      metadataURI10    }11  }12`1314client15  .query({16    query: gql(tokensQuery),17    variables: {18      first: 10,19      orderBy: 'createdAtTimestamp',20      orderDirection: 'desc',21    },22  })23  .then((data) => console.log('Subgraph data: ', data))24  .catch((err) => {25    console.log('Error fetching data: ', err)26  })

              URQL 概述

              URQL⁠可以在 Node.js, React/Preact, Vue 和 Svelte 环境中使用,具有更高级的功能:

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

              通过 URQL 获取数据

              让我们看看如何从 URQL 的子图中获取数据:

              步骤1

              安装 urql 和 graphql:

              1npm install urql graphql

              步骤2

              用以下代码查询API:

              1import { createClient } from 'urql'23const APIURL = 'https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>'45const tokensQuery = `6  query {7    tokens {8      id9      tokenID10      contentURI11      metadataURI12    }13  }14`1516const client = createClient({17  url: APIURL,18})1920const data = await client.query(tokensQuery).toPromise()
              ⁠在GitHub上编辑⁠

              查询最佳实践分布式系统
              在此页面上
              • 获取GraphQL端点
              • 子图工作室端点
              • The Graph网络端点
              • 使用热门GraphQL客户端
              • Graph 客户端
              • 使用 Graph客户端获取数据
              • Apollo 客户端
              • 通过 Apollo 客户端获取数据
              • URQL 概述
              • 通过 URQL 获取数据
              The GraphStatusTestnetBrand AssetsForum安全Privacy PolicyTerms of Service