Consultando > Consultar desde una Aplicación

Consultar desde una Aplicación

Reading time: 4 min

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

Subgraph Studio (endpoint de prueba)

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

Graph Explorer

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

Usando el endpoint de GraphQL, puedes usar varias librerías de Clientes de GraphQL para consultar el subgrafo y rellenar tu aplicación con los datos indexados por el subgrafo.

A continuación se presentan un par de clientes GraphQL más populares en el ecosistema y cómo utilizarlos:

Clientes de GraphQL

Enlace a esta sección

Cliente de Graph

Enlace a esta sección

The Graph proporciona su propio cliente GraphQL, graph-client, que admite características únicas como:

  • Manejo de subgrafos cross-chain: consultas desde múltiples subgrafos en una sola consulta
  • Automatic Block Tracking
  • Automatic Pagination
  • Resultado completamente tipificado

Also integrated with popular GraphQL clients such as Apollo and URQL and compatible with all environments (React, Angular, Node.js, React Native), using graph-client will give you the best experience for interacting with The Graph.

Let's look at how to fetch data from a subgraph with graphql-client.

To get started, make sure to install The Graph Client CLI in your project:

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

Define your query in a .graphql file (or inlined in your .js or .ts file):

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

Then, 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

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

graphclient build

Finally, 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 notice

graph-client is perfectly integrated with other GraphQL clients such as Apollo client, URQL, or React Query; you will 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 get to use Cross-chain Subgraph Handling or Automatic Pagination, which are core features for querying The Graph.

Cliente Apollo

Enlace a esta sección

Apollo client is the ubiquitous GraphQL client on the front-end ecosystem.

Available for React, Angular, Vue, Ember, iOS, and Android, Apollo Client, although the heaviest client, brings many features to build advanced UI on top of GraphQL:

  • advanced error handling (manejo avanzado de errores)
  • pagination (paginado)
  • data prefetching (captura previa de datos)
  • optimistic UI (interfaz de usuario optimista)
  • local state management (gestión de estado local)

Let's look at how to fetch data from a subgraph with Apollo client in a web project.

First, install @apollo/client and graphql:

npm install @apollo/client graphql

A continuación, puedes consultar la API con el siguiente código:

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

To use variables, you can pass in a variables argument to the query:

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

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

  • Flexible cache system (Sistema de caché flexible)
  • Extensible design (Diseño extensible, que facilita agregar nuevas capacidades encima)
  • Lightweight bundle (Paquete ligero, ~5 veces más ligero que Apollo Client)
  • Soporte para carga de archivos y modo fuera de línea

Let's look at how to fetch data from a subgraph with URQL in a web project.

First, install urql and graphql:

npm install urql graphql

A continuación, puedes consultar la API con el siguiente código:

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()
Editar página

Anterior
Mejores Prácticas para Consultas
Siguiente
Sistemas Distribuidos
Editar página