クエリのベストプラクティス
Reading time: 11 min
The Graph provides a decentralized way to query data from blockchains. Its data is exposed through a GraphQL API, making it easier to query with the GraphQL language.
Learn the essential GraphQL language rules and best practices to optimize your subgraph.
REST APIとは異なり、GraphQL APIは実行可能なクエリを定義するSchemaをベースに構築されています。
例えば、token
クエリを使ってトークンを取得するクエリは次のようになります。
query GetToken($id: ID!) {token(id: $id) {idowner}}
以下のような予測可能なJSONレスポンスが返ってきます(適切な$id
変数値を渡す場合)。
{"token": {"id": "...","owner": "..."}}
GraphQLクエリは、で定義されているGraphQL言語を使用します。
上記の GetToken
クエリは、複数の言語部分で構成されています (以下では [...]
プレースホルダーに置き換えられています)。
query [operationName]([variableName]: [variableType]) {[queryName]([argumentName]: [variableName]) {# "{ ... }" express a Selection-Set, we are querying fields from `queryName`.[field][field]}}
- 各
queryName
は、1回の操作で1回だけ使用しなければなりません。 - 各
フィールド
は、選択の中で一度だけ使用しなければなりません(トークン
の下にid
を二度照会することはできません)。 - Some
field
s or queries (liketokens
) return complex types that require a selection of sub-field. Not providing a selection when expected (or providing one when not expected - for example, onid
) will raise an error. To know a field type, please refer to . - 引数に代入される変数は、その型と一致しなければなりません。
- 与えられた変数のリストにおいて、各変数は一意でなければなりません。
- 定義された変数はすべて使用する必要があります。
Note: Failing to follow these rules will result in an error from The Graph API.
For a complete list of rules with code examples, check out .
GraphQL is a language and set of conventions that transport over HTTP.
It means that you can query a GraphQL API using standard fetch
(natively or via @whatwg-node/fetch
or isomorphic-fetch
).
However, as mentioned in , it's recommended to use graph-client
, which supports the following unique features:
Here's how to query The Graph with graph-client
:
import { execute } from '../.graphclient'const query = `query GetToken($id: ID!) {token(id: $id) {idowner}}`const variables = { id: '1' }async function main() {const result = await execute(query, variables)// `result` is fully typed!console.log(result)}main()
More GraphQL client alternatives are covered in .
A common (bad) practice is to dynamically build query strings as follows:
const id = params.idconst fields = ['id', 'owner']const query = `query GetToken {token(id: ${id}) {${fields.join('\n')}}}`// Execute query...
While the above snippet produces a valid GraphQL query, it has many drawbacks:
- クエリ全体を理解するのが難しくなります。
- 開発者は、文字列補間を安全にサニタイズする責任があるということです。
- リクエストパラメータの一部として変数の値を送信しないでください。サーバー側でのキャッシュの可能性を防止
- それは ** ツールがクエリを静的に分析するのを防ぐ** (例: Linter、またはタイプ生成ツール) です。
For this reason, it is recommended to always write queries as static strings:
import { execute } from 'your-favorite-graphql-client'const id = params.idconst query = `query GetToken($id: ID!) {token(id: $id) {idowner}}`const result = await execute(query, {variables: {id,},})
Doing so brings many advantages:
- 読みやすく、メンテナンスしやすいクエリ
- GraphQLのサーバーは、変数のサニタイズを処理します
- サーバーレベルで変数がキャッシュできます。
- ツールでクエリを静的に分析できる(これについては、次のセクションで詳しく説明します。)
You might want to include the owner
field only on a particular condition.
For this, you can leverage the @include(if:...)
directive as follows:
import { execute } from 'your-favorite-graphql-client'const id = params.idconst query = `query GetToken($id: ID!, $includeOwner: Boolean) {token(id: $id) {idowner @include(if: $includeOwner)}}`const result = await execute(query, {variables: {id,includeOwner: true,},})
Note: The opposite directive is @skip(if: ...)
.
GraphQL became famous for its "Ask for what you want" tagline.
For this reason, there is no way, in GraphQL, to get all available fields without having to list them individually.
- GraphQL APIをクエリする際には、実際に使用するフィールドのみをクエリするように常に考えてください。
- Make sure queries only fetch as many entities as you actually need. By default, queries will fetch 100 entities in a collection, which is usually much more than what will actually be used, e.g., for display to the user. This applies not just to top-level collections in a query, but even more so to nested collections of entities.
For example, in the following query:
query listTokens {tokens {# will fetch up to 100 tokensidtransactions {# will fetch up to 100 transactionsid}}}
The response could contain 100 transactions for each of the 100 tokens.
If the application only needs 10 transactions, the query should explicitly set first: 10
on the transactions field.
By default, subgraphs have a singular entity for one record. For multiple records, use the plural entities and filter: where: {id_in:[X,Y,Z]}
or where: {volume_gt:100000}
Example of inefficient querying:
query SingleRecord {entity(id: X) {idname}}query SingleRecord {entity(id: Y) {idname}}
Example of optimized querying:
query ManyRecords {entities(where: { id_in: [X, Y] }) {idname}}
Your application might require querying multiple types of data as follows:
import { execute } from "your-favorite-graphql-client"const tokensQuery = `query GetTokens {tokens(first: 50) {idowner}}`const countersQuery = `query GetCounters {counters {idvalue}}`const [tokens, counters] = Promise.all([tokensQuery,countersQuery,].map(execute))
While this implementation is totally valid, it will require two round trips with the GraphQL API.
Fortunately, it is also valid to send multiple queries in the same GraphQL request as follows:
import { execute } from "your-favorite-graphql-client"const query = `query GetTokensandCounters {tokens(first: 50) {idowner}counters {idvalue}}`
This approach will improve the overall performance by reducing the time spent on the network (saves you a round trip to the API) and will provide a more concise implementation.
A helpful feature to write GraphQL queries is GraphQL Fragment.
Looking at the following query, you will notice that some fields are repeated across multiple Selection-Sets ({ ... }
):
query {bondEvents {idnewDelegate {idactivestatus}oldDelegate {idactivestatus}}}
Such repeated fields (id
, active
, status
) bring many issues:
- More extensive queries become harder to read.
- When using tools that generate TypeScript types based on queries (more on that in the last section),
newDelegate
andoldDelegate
will result in two distinct inline interfaces.
A refactored version of the query would be the following:
query {bondEvents {idnewDelegate {...DelegateItem}oldDelegate {...DelegateItem}}}# we define a fragment (subtype) on Transcoder# to factorize repeated fields in the queryfragment DelegateItem on Transcoder {idactivestatus}
Using GraphQL fragment
will improve readability (especially at scale) and result in better TypeScript types generation.
When using the types generation tool, the above query will generate a proper DelegateItemFragment
type (see last "Tools" section).
A Fragment cannot be based on a non-applicable type, in short, on type not having fields:
fragment MyFragment on BigInt {# ...}
BigInt
is a scalar (native "plain" type) that cannot be used as a fragment's base.
Fragments are defined on specific types and should be used accordingly in queries.
例:
query {bondEvents {idnewDelegate {...VoteItem # Error! `VoteItem` cannot be spread on `Transcoder` type}oldDelegate {...VoteItem}}}fragment VoteItem on Vote {idvoter}
newDelegate
and oldDelegate
are of type Transcoder
.
It is not possible to spread a fragment of type Vote
here.
GraphQL Fragment
s must be defined based on their usage.
For most use-case, defining one fragment per type (in the case of repeated fields usage or type generation) is sufficient.
Here is a rule of thumb for using fragments:
- When fields of the same type are repeated in a query, group them in a
Fragment
. - When similar but different fields are repeated, create multiple fragments, for instance:
# base fragment (mostly used in listing)fragment Voter on Vote {idvoter}# extended fragment (when querying a detailed view of a vote)fragment VoteWithPoll on Vote {idvoterchoiceIDpoll {idproposal}}
Iterating over queries by running them in your application can be cumbersome. For this reason, don't hesitate to use to test your queries before adding them to your application. Graph Explorer will provide you a preconfigured GraphQL playground to test your queries.
If you are looking for a more flexible way to debug/test your queries, other similar web-based tools are available such as and .
In order to keep up with the mentioned above best practices and syntactic rules, it is highly recommended to use the following workflow and IDE tools.
GraphQL ESLint
will help you stay on top of GraphQL best practices with zero effort.
config will enforce essential rules such as:
@graphql-eslint/fields-on-correct-type
: フィールドは適切なタイプで使用されているか?@graphql-eslint/no-unused variables
: 与えられた変数は未使用のままであるべきか?- ともっと
This will allow you to catch errors without even testing queries on the playground or running them in production!
VSCode and GraphQL
The is an excellent addition to your development workflow to get:
- Syntax highlighting
- Autocomplete suggestions
- Validation against schema
- Snippets
- Go to definition for fragments and input types
If you are using graphql-eslint
, the is a must-have to visualize errors and warnings inlined in your code correctly.
WebStorm/Intellij and GraphQL
The will significantly improve your experience while working with GraphQL by providing:
- Syntax highlighting
- Autocomplete suggestions
- Validation against schema
- Snippets
For more information on this topic, check out the which showcases all the plugin's main features.