Skip to content

Commit 33522cc

Browse files
authored
doc(querying): replace code examples with graph-client (#183)
* doc(querying): replace code examples with `graph-client` * doc: move "Querying Best Practices" above "Querying from an Application" * doc(querying): Grammarly pass * doc(querying): Grammarly fixes
1 parent efe4888 commit 33522cc

File tree

3 files changed

+171
-118
lines changed

3 files changed

+171
-118
lines changed

navigation/navigation.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,10 @@ export const navigation = (locale: AppLocale): NavItemDefinition[] => [
115115
slug: 'managing-api-keys',
116116
},
117117
{
118-
slug: 'querying-from-an-application',
118+
slug: 'querying-best-practices',
119119
},
120120
{
121-
slug: 'querying-best-practices',
121+
slug: 'querying-from-an-application',
122122
},
123123
{
124124
slug: 'distributed-systems',

pages/en/querying/querying-best-practices.mdx

Lines changed: 21 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,21 @@ For a complete list of rules with code examples, please look at our GraphQL Vali
7171

7272
GraphQL is a language and set of conventions that transport over HTTP.
7373

74-
It means that you can query a GraphQL API using standard `fetch` (natively or via `cross-undici-fetch` or `isomorphic-fetch`) as follows:
74+
It means that you can query a GraphQL API using standard `fetch` (natively or via `@whatwg-node/fetch` or `isomorphic-fetch`).
75+
76+
However, as stated in ["Querying from an Application"](/querying/querying-from-an-application), we recommend you to use our `graph-client` that supports unique features such as:
77+
- Cross-chain Subgraph Handling: Querying from multiple subgraphs in a single query
78+
- [Automatic Block Tracking](https://github.com/graphprotocol/graph-client/blob/main/packages/block-tracking/README.md)
79+
- [Automatic Pagination](https://github.com/graphprotocol/graph-client/blob/main/packages/auto-pagination/README.md)
80+
- Fully typed result
81+
82+
<br />
83+
84+
Here's how to query The Graph with `graph-client`:
7585

7686
```tsx
87+
import { execute } from '../.graphclient'
88+
7789
const query = `
7890
query GetToken($id: ID!) {
7991
token(id: $id) {
@@ -84,55 +96,16 @@ query GetToken($id: ID!) {
8496
`
8597
const variables = { id: '1' }
8698

87-
const fetchResult = await fetch('http://example.com/graphql', {
88-
method: 'POST',
89-
headers: { 'Content-Type': 'application/json' },
90-
body: JSON.stringify({ query, variables }),
91-
})
92-
const result = await fetchResult.json()
93-
```
94-
95-
Another lightweight alternative, best for back-end use-cases, is the famous [`graphql-request` library](https://github.com/prisma-labs/graphql-request).
96-
97-
This lightweight GraphQL client comes with the essential features to query a GraphQL API:
98-
99-
- Mutations validation
100-
- Support for file upload
101-
- Batching
102-
- Promise-based API
103-
- TypeScript support
104-
105-
<br />
106-
107-
A complete GraphQL client is [URQL](https://formidable.com/open-source/urql/) which is available within Node.js, React/Preact, Vue, Svelte environments, with more advanced features:
108-
109-
- Flexible cache system
110-
- Extensible design (easing adding new capabilities on top of it)
111-
- Lightweight bundle (~5x lighter than Apollo Client)
112-
- Support for file uploads and offline mode
113-
114-
<br />
115-
116-
In the React ecosystem, [React Query](https://react-query.tanstack.com/graphql) brings a lightweight and agnostic solution for GraphQL.
117-
118-
React Query is a great candidate if you are looking for an easy-to-use and lightweight multipurpose client (GraphQL-capable) that provides essential features such as:
119-
120-
- Powerful cache (background refresh, window-focus refreshing)
121-
- Advanced querying pattern (parallel queries, dependent queries, prefetching)
122-
- UX patterns: optimistic updates, scroll restoration
123-
- Great dev tools
124-
125-
<br />
126-
127-
Finally, Apollo Client is the ubiquitous GraphQL client on the front-end ecosystem.
99+
async function main() {
100+
const result = await execute(query, variables)
101+
// `result` is fully typed!
102+
console.log(result)
103+
}
128104

129-
Available for React, Angular, Vue, Ember, iOS, and Android, Apollo Client, although the heaviest clients, brings many features to build advanced UI on-top of GraphQL:
105+
main()
106+
```
130107

131-
- advanced error handling
132-
- pagination
133-
- data prefetching
134-
- optimistic UI
135-
- local state management
108+
More GraphQL client alternatives are covered in ["Querying from an Application"](/querying/querying-from-an-application).
136109

137110
<br />
138111

@@ -503,69 +476,3 @@ The [JS GraphQL plugin](https://plugins.jetbrains.com/plugin/8097-graphql/) will
503476
- snippets
504477

505478
More information on this [WebStorm article](https://blog.jetbrains.com/webstorm/2019/04/featured-plugin-js-graphql/) that showcases all the plugin's main features.
506-
507-
<br />
508-
509-
### TypeScript types generation
510-
511-
Finally, the best GraphQL experience is reached when the TypeScript data types are generated from the defined GraphQL queries, as follows:
512-
513-
```tsx
514-
import { execute } from 'your-favorite-graphql-client'
515-
import { GetTokenQuery } from './generated.'
516-
517-
const id = params.id
518-
const query = `
519-
query GetToken($id: ID!) {
520-
token(id: $id) {
521-
id
522-
owner
523-
}
524-
}
525-
`
526-
527-
const result: GetTokenQuery = await execute(query, {
528-
variables: {
529-
id,
530-
},
531-
})
532-
533-
// `result` is typed!
534-
```
535-
536-
Such a setup can be easily achieved by installing and configuring [GraphQL Code Generator](https://www.graphql-code-generator.com/docs/getting-started) as follows:
537-
538-
```bash
539-
yarn add graphql @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations
540-
```
541-
542-
Then update your `package.json` (or similar script configuration setup) as follows:
543-
544-
```tsx
545-
{
546-
// ...
547-
"scripts": {
548-
// ...
549-
"generate": "graphql-codegen",
550-
// ...
551-
}
552-
// ...
553-
}
554-
```
555-
556-
Add the following configuration file to your project:
557-
558-
```tsx
559-
schema: "<SUBGRAPH_URL>"
560-
documents: './src/**/*.ts'
561-
generates:
562-
./generated.ts:
563-
plugins:
564-
- typescript
565-
- typescript-operations
566-
```
567-
568-
Finally, by simply running the configured script (`yarn generate`), GraphQL Code Generator will generate the proper TypeScript types in the `generated.ts` file:
569-
570-
- Each query will get a corresponding `[QueryName]Query` type (ex: `GetToken``GetTokenQuery` type
571-
- Each fragment will get a corresponding `[FragmentName]Fragment` type (ex: `DelegateItem``DelegateItemFragment` type

pages/en/querying/querying-from-an-application.mdx

Lines changed: 148 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,146 @@ Using the GraphQL endpoint, you can use various GraphQL Client libraries to quer
2222

2323
Here are a couple of the more popular GraphQL clients in the ecosystem and how to use them:
2424

25+
## GraphQL clients
26+
27+
28+
### Graph client
29+
30+
The Graph is providing it own GraphQL client, `graph-client` that supports unique features such as:
31+
- Cross-chain Subgraph Handling: Querying from multiple subgraphs in a single query
32+
- [Automatic Block Tracking](https://github.com/graphprotocol/graph-client/blob/main/packages/block-tracking/README.md)
33+
- [Automatic Pagination](https://github.com/graphprotocol/graph-client/blob/main/packages/auto-pagination/README.md)
34+
- Fully typed result
35+
36+
<br />
37+
38+
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.
39+
40+
<br />
41+
42+
Let's look at how to fetch data from a subgraph with `graphql-client`.
43+
44+
To get started, make sure to install The Graph Client CLI in your project:
45+
46+
```sh
47+
yarn add -D @graphprotocol/client-cli
48+
# or, with NPM:
49+
npm install --save-dev @graphprotocol/client-cli
50+
```
51+
52+
Define you query in a `.graphql` file (or inlined in your `.js` or `.ts` file):
53+
54+
```graphql
55+
query ExampleQuery {
56+
# this one is coming from compound-v2
57+
markets(first: 7) {
58+
borrowRate
59+
cash
60+
collateralFactor
61+
}
62+
# this one is coming from uniswap-v2
63+
pair(id: "0x00004ee988665cdda9a1080d5792cecd16dc1220") {
64+
id
65+
token0 {
66+
id
67+
symbol
68+
name
69+
}
70+
token1 {
71+
id
72+
symbol
73+
name
74+
}
75+
}
76+
}
77+
```
78+
79+
80+
Then, create a configuration file (called `.graphclientrc.yml`) and point to your GraphQL endpoints provided by The Graph, for example:
81+
82+
```yaml
83+
# .graphclientrc.yml
84+
sources:
85+
- name: uniswapv2
86+
handler:
87+
graphql:
88+
endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2
89+
- name: compoundv2
90+
handler:
91+
graphql:
92+
endpoint: https://api.thegraph.com/subgraphs/name/graphprotocol/compound-v2
93+
94+
documents:
95+
- ./src/example-query.graphql
96+
```
97+
98+
Running the following The Graph Client CLI command will generate typed and ready to use JavaScript code:
99+
100+
```sh
101+
graphclient build
102+
```
103+
104+
Finally, update your `.ts` file to use the generated typed GraphQL documents:
105+
106+
```tsx
107+
import React, { useEffect } from 'react'
108+
// ...
109+
// we import types and typed-graphql document from the generated code (`..graphclient/`)
110+
import { ExampleQueryDocument, ExampleQueryQuery, execute } from '../.graphclient'
111+
112+
function App() {
113+
const [data, setData] = React.useState<ExampleQueryQuery>()
114+
115+
useEffect(() => {
116+
execute(ExampleQueryDocument, {}).then((result) => {
117+
setResult(result?.data)
118+
})
119+
}, [])
120+
return (
121+
<div className="App">
122+
<header className="App-header">
123+
<img src={logo} className="App-logo" alt="logo" />
124+
<p>Graph Client Example</p>
125+
<fieldset>
126+
{data && (
127+
<form>
128+
<label>Data</label>
129+
<br />
130+
<textarea value={JSON.stringify(result.data, null, 2)} readOnly rows={25} />
131+
</form>
132+
)}
133+
</fieldset>
134+
</header>
135+
</div>
136+
)
137+
}
138+
139+
export default App
140+
```
141+
142+
<br />
143+
144+
**⚠️ Important notice**
145+
146+
`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](https://github.com/graphprotocol/graph-client/tree/main/examples).
147+
148+
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**.
149+
150+
<br />
151+
25152
### Apollo client
26153

27-
[Apollo client](https://www.apollographql.com/docs/) supports web projects, including frameworks like React and Vue, as well as mobile clients like iOS, Android, and React Native.
154+
[Apollo client](https://www.apollographql.com/docs/) is the ubiquitous GraphQL client on the front-end ecosystem.
155+
156+
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:
157+
158+
- advanced error handling
159+
- pagination
160+
- data prefetching
161+
- optimistic UI
162+
- local state management
163+
164+
<br />
28165

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

@@ -98,9 +235,18 @@ client
98235
})
99236
```
100237

238+
<br />
239+
101240
### URQL
102241

103-
Another option is [URQL](https://formidable.com/open-source/urql/), a somewhat lighter-weight GraphQL client library.
242+
Another option is [URQL](https://formidable.com/open-source/urql/) which is available within Node.js, React/Preact, Vue, and Svelte environments, with more advanced features:
243+
244+
- Flexible cache system
245+
- Extensible design (easing adding new capabilities on top of it)
246+
- Lightweight bundle (~5x lighter than Apollo Client)
247+
- Support for file uploads and offline mode
248+
249+
<br />
104250

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

0 commit comments

Comments
 (0)