Skip to content

Commit a041f40

Browse files
committed
New translations best-practices.mdx (Portuguese)
1 parent a0364b2 commit a041f40

File tree

1 file changed

+84
-84
lines changed

1 file changed

+84
-84
lines changed

website/src/pages/pt/subgraphs/querying/best-practices.mdx

Lines changed: 84 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -52,31 +52,31 @@ query [operationName]([variableName]: [variableType]) {
5252

5353
## Regras para Escrever Queries em GraphQL
5454

55-
- Each `queryName` must only be used once per operation.
56-
- Each `field` must be used only once in a selection (we cannot query `id` twice under `token`)
57-
- Some `field`s or queries (like `tokens`) return complex types that require a selection of sub-field. Not providing a selection when expected (or providing one when not expected - for example, on `id`) will raise an error. To know a field type, please refer to [Graph Explorer](/subgraphs/explorer/).
55+
- Cada `queryName` só pode ser usado uma vez por operação.
56+
- Cada `field` deve ser usado apenas uma vez numa seleção (não podemos solicitar a `id` duas vezes sob o `token`)
57+
- Alguns `field`s ou queries (como `tokens`) retornam tipos complexos que exigem uma seleção de sub-campo. Caso uma seleção não seja fornecida quando esperada (ou fornecida quando não é esperada — por exemplo, em `id`), aparecerá um erro. Para conhecer um tipo de campo, consulte o [Graph Explorer](/subgraphs/explorer/).
5858
- Qualquer variável apontada a um argumento deve corresponder ao seu tipo.
5959
- Em uma lista dada de variáveis, cada uma delas deve ser única.
6060
- Todas as variáveis definidas devem ser usadas.
6161

62-
> Note: Failing to follow these rules will result in an error from The Graph API.
62+
> Não seguir as regras acima causará um erro da API do The Graph.
6363
64-
For a complete list of rules with code examples, check out [GraphQL Validations guide](/resources/release-notes/graphql-validations-migration-guide/).
64+
Para uma lista completa de regras com exemplos de código, veja o [guia de Validações da GraphQL](/resources/release-notes/graphql-validations-migration-guide/).
6565

6666
### Como enviar um query a uma API GraphQL
6767

68-
GraphQL is a language and set of conventions that transport over HTTP.
68+
GraphQL é uma linguagem e um conjunto de convenções transportadas através do HTTP.
6969

70-
It means that you can query a GraphQL API using standard `fetch` (natively or via `@whatwg-node/fetch` or `isomorphic-fetch`).
70+
Ou seja, dá para fazer um query numa API GraphQL com o `fetch` normal (nativamente ou via `@whatwg-node/fetch` ou `isomorphic-fetch`).
7171

72-
However, as mentioned in ["Querying from an Application"](/subgraphs/querying/from-an-application/), it's recommended to use `graph-client`, which supports the following unique features:
72+
Porém, conforme mencionado em ["Como Fazer Queries de Um Aplicativo"](/subgraphs/querying/from-an-application/), recomendamos usar o `graph-client`, que apoia as seguintes funções únicas:
7373

7474
- Gestão de Subgraph Cross-chain: Queries de múltiplos subgraphs numa única consulta
75-
- [Automatic Block Tracking](https://github.com/graphprotocol/graph-client/blob/main/packages/block-tracking/README.md)
76-
- [Automatic Pagination](https://github.com/graphprotocol/graph-client/blob/main/packages/auto-pagination/README.md)
75+
- [Rastreamento Automático de Blocos](https://github.com/graphprotocol/graph-client/blob/main/packages/block-tracking/README.md)
76+
- [Paginação Automática](https://github.com/graphprotocol/graph-client/blob/main/packages/auto-pagination/README.md)
7777
- Resultado totalmente digitado
7878

79-
Here's how to query The Graph with `graph-client`:
79+
Aqui está como fazer queries para o The Graph com o `graph-client`:
8080

8181
```tsx
8282
import { execute } from '../.graphclient'
@@ -100,15 +100,15 @@ async function main() {
100100
main()
101101
```
102102

103-
More GraphQL client alternatives are covered in ["Querying from an Application"](/subgraphs/querying/from-an-application/).
103+
Para mais alternativas de clientes para GraphQL, veja ["Como Fazer Queries de Um Aplicativo"](/subgraphs/querying/from-an-application/).
104104

105105
---
106106

107107
## Boas práticas
108108

109109
### Sempre escreva consultas estáticas
110110

111-
A common (bad) practice is to dynamically build query strings as follows:
111+
É (um erro) comum construir strings de query dinamicamente, como no exemplo a seguir:
112112

113113
```tsx
114114
const id = params.id
@@ -124,14 +124,14 @@ query GetToken {
124124
// Execute query...
125125
```
126126

127-
While the above snippet produces a valid GraphQL query, **it has many drawbacks**:
127+
Enquanto o trecho acima produz um query válido na GraphQL, **isto traz muitas desvantagens**:
128128

129-
- it makes it **harder to understand** the query as a whole
130-
- developers are **responsible for safely sanitizing the string interpolation**
131-
- not sending the values of the variables as part of the request parameters **prevent possible caching on server-side**
132-
- it **prevents tools from statically analyzing the query** (ex: Linter, or type generations tools)
129+
- deixa o query **mais difícil de entender**
130+
- os programadores são **responsáveis por higienizar a interpolação de string com segurança**
131+
- não enviar os valores das variáveis como parte dos parâmetros de pedido **impede um possível caching no lado do servidor**
132+
- isto **impede as ferramentas de analisar o query estaticamente** (por ex. Linter ou ferramentas de geração de tipos)
133133

134-
For this reason, it is recommended to always write queries as static strings:
134+
Por isto, é recomendado sempre escrever queries como strings estáticas:
135135

136136
```tsx
137137
import { execute } from 'your-favorite-graphql-client'
@@ -153,18 +153,18 @@ const result = await execute(query, {
153153
})
154154
```
155155

156-
Doing so brings **many advantages**:
156+
Isto traz **muitas vantagens**:
157157

158-
- **Easy to read and maintain** queries
159-
- The GraphQL **server handles variables sanitization**
160-
- **Variables can be cached** at server-level
161-
- **Queries can be statically analyzed by tools** (more on this in the following sections)
158+
- Queries **fáceis de ler e manter**
159+
- O servidor GraphQL **cuida da higienização de variáveis**
160+
- **Variáveis podem ser guardadas em cache** no nível do servidor
161+
- **Queries podem ser analisados estaticamente por ferramentas** (mais sobre isto nas secções seguintes)
162162

163-
### How to include fields conditionally in static queries
163+
### Como incluir campos condicionalmente em queries estáticos
164164

165-
You might want to include the `owner` field only on a particular condition.
165+
Talvez queira incluir o campo `owner` apenas com uma condição particular.
166166

167-
For this, you can leverage the `@include(if:...)` directive as follows:
167+
Para isto, use a diretiva `@include(if:...)` a seguir:
168168

169169
```tsx
170170
import { execute } from 'your-favorite-graphql-client'
@@ -187,18 +187,18 @@ const result = await execute(query, {
187187
})
188188
```
189189

190-
> Note: The opposite directive is `@skip(if: ...)`.
190+
> Observação: a diretiva oposta é `@skip(if: ...)`.
191191
192192
### Pergunte pelo que queres
193193

194-
GraphQL became famous for its "Ask for what you want" tagline.
194+
A GraphQL ficou famosa por sua frase de efeito "pergunte pelo que queres".
195195

196-
For this reason, there is no way, in GraphQL, to get all available fields without having to list them individually.
196+
Por isto, no GraphQL, não há como obter todos os campos disponíveis sem ter que listá-los individualmente.
197197

198198
- Ao consultar APIs GraphQL, sempre considere fazer query apenas dos campos que serão usados.
199-
- 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.
199+
- Tenha certeza que os queries só retornarão o máximo necessário de entidades. Por natureza, os queries retirarão 100 entidades em uma coleção, muito mais do que realmente será usado; por ex., para fins de amostra ao usuário. Isto serve não só para coleções de alto nível em um query, mas também — especialmente — para coleções aninhadas de entidades.
200200

201-
For example, in the following query:
201+
Por exemplo, no query seguinte:
202202

203203
```graphql
204204
query listTokens {
@@ -213,15 +213,15 @@ query listTokens {
213213
}
214214
```
215215

216-
The response could contain 100 transactions for each of the 100 tokens.
216+
A resposta pode conter 100 transações para cada um dos 100 tokens.
217217

218-
If the application only needs 10 transactions, the query should explicitly set `first: 10` on the transactions field.
218+
Se o aplicativo só precisa de 10 transações, o query deve configurar explicitamente `first: 10` no campo de transações.
219219

220220
### Use uma única query para pedir vários registros
221221

222-
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}`
222+
Por padrão, subgraphs têm uma entidade singular para um registro. Para múltiplos registros, use as entidades plurais e o filtro: `where: {id_in:[X,Y,Z]}` ou `where: {volume_gt:100000}`
223223

224-
Example of inefficient querying:
224+
Um exemplo de query ineficaz:
225225

226226
```graphql
227227
query SingleRecord {
@@ -238,7 +238,7 @@ query SingleRecord {
238238
}
239239
```
240240

241-
Example of optimized querying:
241+
Um exemplo de query otimizado:
242242

243243
```graphql
244244
query ManyRecords {
@@ -251,7 +251,7 @@ query ManyRecords {
251251

252252
### Combine múltiplas queries em um único pedido
253253

254-
Your application might require querying multiple types of data as follows:
254+
O seu aplicativo pode exigir queries de múltiplos tipos de dados, como a seguir:
255255

256256
```graphql
257257
import { execute } from "your-favorite-graphql-client"
@@ -281,9 +281,9 @@ const [tokens, counters] = Promise.all(
281281
)
282282
```
283283

284-
While this implementation is totally valid, it will require two round trips with the GraphQL API.
284+
Enquanto esta implementação é totalmente válida, ela exigirá duas rondas totais com a API da GraphQL.
285285

286-
Fortunately, it is also valid to send multiple queries in the same GraphQL request as follows:
286+
Felizmente, também vale enviar múltiplos queries no mesmo pedido à GraphQL, como a seguir:
287287

288288
```graphql
289289
import { execute } from "your-favorite-graphql-client"
@@ -304,13 +304,13 @@ query GetTokensandCounters {
304304
const { result: { tokens, counters } } = execute(query)
305305
```
306306

307-
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**.
307+
Este método **melhorará o desempenho em geral** ao reduzir o tempo gasto na rede (porque poupa uma viagem ao redor da API) e fornecerá **implementações mais concisas**.
308308

309309
### Como Aproveitar Fragmentos GraphQL
310310

311-
A helpful feature to write GraphQL queries is GraphQL Fragment.
311+
O GraphQL Fragment é uma ferramenta útil para a escrita de queries em GraphQL.
312312

313-
Looking at the following query, you will notice that some fields are repeated across multiple Selection-Sets (`{ ... }`):
313+
No seguinte query, perceba que alguns campos são repetidos em vários Selection-Sets (`{ ... }`):
314314

315315
```graphql
316316
query {
@@ -330,12 +330,12 @@ query {
330330
}
331331
```
332332

333-
Such repeated fields (`id`, `active`, `status`) bring many issues:
333+
Estes campos repetidos (`id`, `active`, `status`) trazem muitos problemas:
334334

335-
- More extensive queries become harder to read.
336-
- When using tools that generate TypeScript types based on queries (_more on that in the last section_), `newDelegate` and `oldDelegate` will result in two distinct inline interfaces.
335+
- Queries mais extensos ficam difíceis de ler.
336+
- Ao usar ferramentas que geram tipos TypeScript baseados em queries (_mais na última secção_), `newDelegate` e `oldDelegate` retornarão duas interfaces distintas em inline.
337337

338-
A refactored version of the query would be the following:
338+
Fatorizado novamente, o query ficaria assim:
339339

340340
```graphql
341341
query {
@@ -359,27 +359,27 @@ fragment DelegateItem on Transcoder {
359359
}
360360
```
361361

362-
Using GraphQL `fragment` will improve readability (especially at scale) and result in better TypeScript types generation.
362+
Usar o `fragment` ("fragmento") da GraphQL melhorará a legibilidade (especialmente em escala) e também melhorará a geração de tipos TypeScript.
363363

364-
When using the types generation tool, the above query will generate a proper `DelegateItemFragment` type (_see last "Tools" section_).
364+
Ao usar a ferramenta de geração de tipos, o query acima gerará um tipo `DelegateItemFragment` apropriado (_veja a última secção "Ferramentas"_).
365365

366366
### O que fazer e o que não fazer em Fragments GraphQL
367367

368368
### A base do fragment deve ser um tipo
369369

370-
A Fragment cannot be based on a non-applicable type, in short, **on type not having fields**:
370+
Um Fragment não pode ser baseado num tipo não aplicável; ou seja, **um tipo sem campos**:
371371

372372
```graphql
373373
fragment MyFragment on BigInt {
374374
# ...
375375
}
376376
```
377377

378-
`BigInt` is a **scalar** (native "plain" type) that cannot be used as a fragment's base.
378+
O `BigInt` é um **escalar** (tipo "plano" nativo) que não pode ser usado como a base de um fragmento.
379379

380380
#### Como espalhar um Fragment
381381

382-
Fragments are defined on specific types and should be used accordingly in queries.
382+
Fragmentos são definidos em tipos específicos e devem ser usados de acordo nos queries.
383383

384384
Exemplo:
385385

@@ -402,20 +402,20 @@ fragment VoteItem on Vote {
402402
}
403403
```
404404

405-
`newDelegate` and `oldDelegate` are of type `Transcoder`.
405+
`newDelegate` e `oldDelegate` são do tipo `Transcoder`.
406406

407-
It is not possible to spread a fragment of type `Vote` here.
407+
Não é possível espalhar um fragmento do tipo `Vote` aqui.
408408

409409
#### Defina o Fragment como uma unidade de negócios atômica de dados
410410

411-
GraphQL `Fragment`s must be defined based on their usage.
411+
`Fragment`s da GraphQL devem ser definidos com base no seu uso.
412412

413-
For most use-case, defining one fragment per type (in the case of repeated fields usage or type generation) is sufficient.
413+
Para a maioria dos casos de uso, definir um fragmento por tipo (no caso do uso repetido de campos ou geração de tipos) já é o suficiente.
414414

415-
Here is a rule of thumb for using fragments:
415+
Aqui estão algumas regras básicas para o uso de Fragmentos:
416416

417-
- When fields of the same type are repeated in a query, group them in a `Fragment`.
418-
- When similar but different fields are repeated, create multiple fragments, for instance:
417+
- Quando campos do mesmo tipo se repetem em um query, agrupe-os em um `Fragment`.
418+
- Quando campos parecidos (mas não idênticos) se repetem, crie múltiplos fragmentos, por exemplo:
419419

420420
```graphql
421421
# base fragment (mostly used in listing)
@@ -438,51 +438,51 @@ fragment VoteWithPoll on Vote {
438438

439439
---
440440

441-
## The Essential Tools
441+
## Ferramentas Essenciais
442442

443443
### Exploradores do GraphQL baseados em web
444444

445-
Iterating over queries by running them in your application can be cumbersome. For this reason, don't hesitate to use [Graph Explorer](https://thegraph.com/explorer) to test your queries before adding them to your application. Graph Explorer will provide you a preconfigured GraphQL playground to test your queries.
445+
Pode ser até chato executar queries no seu aplicativo para iterar sobre elas. Por isto, não hesite em usar o [Graph Explorer](https://thegraph.com/explorer) para testar os seus queries antes de adicioná-los. O Graph Explorer fornecerá um ambiente de testes GraphQL pré-configurado para testar os seus queries.
446446

447-
If you are looking for a more flexible way to debug/test your queries, other similar web-based tools are available such as [Altair](https://altairgraphql.dev/) and [GraphiQL](https://graphiql-online.com/graphiql).
447+
Se procura uma maneira mais flexível de depurar/testar seus queries, há outras ferramentas semelhantes baseadas na web, como [Altair](https://altairgraphql.dev/) e [GraphiQL](https://graphiql-online.com/graphiql).
448448

449449
### GraphQL Linting
450450

451-
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.
451+
Para acompanhar as melhores práticas e regras sintáticas explicadas acima, vale muito a pena utilizar as ferramentas IDE e de fluxo de trabalho a seguir.
452452

453-
**GraphQL ESLint**
453+
**ESLint — GraphQL**
454454

455-
[GraphQL ESLint](https://the-guild.dev/graphql/eslint/docs/getting-started) will help you stay on top of GraphQL best practices with zero effort.
455+
O [ESLint da GraphQL](https://the-guild.dev/graphql/eslint/docs/getting-started) te ajudará a acompanhar as melhores práticas da GraphQL sem sofrimento.
456456

457-
[Setup the "operations-recommended"](https://the-guild.dev/graphql/eslint/docs/configs) config will enforce essential rules such as:
457+
[Organize a configuração "operations-recommended"](https://the-guild.dev/graphql/eslint/docs/configs) para executar regras essenciais como:
458458

459-
- `@graphql-eslint/fields-on-correct-type`: is a field used on a proper type?
460-
- `@graphql-eslint/no-unused variables`: should a given variable stay unused?
459+
- `@graphql-eslint/fields-on-correct-type`: um campo está num tipo apropriado?
460+
- `@graphql-eslint/no-unused variables`: uma variável usada deve ficar sem uso?
461461
- e mais!
462462

463-
This will allow you to **catch errors without even testing queries** on the playground or running them in production!
463+
Isto permitirá-lhe **detetar erros mesmo sem testar queries** no playground ou mesmo executá-los na produção!
464464

465465
### Plugins IDE
466466

467-
**VSCode and GraphQL**
467+
**VSCode e GraphQL**
468468

469-
The [GraphQL VSCode extension](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql) is an excellent addition to your development workflow to get:
469+
A [extensão VSCode da GraphQL](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql) é uma adição excelente ao seu fluxo de programação que permite:
470470

471-
- Syntax highlighting
472-
- Autocomplete suggestions
473-
- Validation against schema
474-
- Snippets
475-
- Go to definition for fragments and input types
471+
- Destaque de sintaxe
472+
- Sugestões de preenchimento automático
473+
- Validação perante schema
474+
- Snippets (blocos de código reutilizáveis)
475+
- Definições de fragmentos e tipos de entrada
476476

477-
If you are using `graphql-eslint`, the [ESLint VSCode extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) is a must-have to visualize errors and warnings inlined in your code correctly.
477+
Se utilizar o `graphql-eslint`, a [extensão VSCode para o ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) é essencial para visualizar corretamente erros e avisos embutidos no seu código.
478478

479-
**WebStorm/Intellij and GraphQL**
479+
**WebStorm/Intellij e GraphQL**
480480

481-
The [JS GraphQL plugin](https://plugins.jetbrains.com/plugin/8097-graphql/) will significantly improve your experience while working with GraphQL by providing:
481+
O [plugin JavaScript para a GraphQL](https://plugins.jetbrains.com/plugin/8097-graphql/) melhorará muito a sua experiência com a GraphQL com:
482482

483-
- Syntax highlighting
484-
- Autocomplete suggestions
485-
- Validation against schema
486-
- Snippets
483+
- Destaque de sintaxe
484+
- Sugestões de preenchimento automático
485+
- Validação perante schema
486+
- Snippets (blocos de código reutilizáveis)
487487

488-
For more information on this topic, check out the [WebStorm article](https://blog.jetbrains.com/webstorm/2019/04/featured-plugin-js-graphql/) which showcases all the plugin's main features.
488+
Para mais informações sobre este tópico, veja o [artigo do WebStorm](https://blog.jetbrains.com/webstorm/2019/04/featured-plugin-js-graphql/), que demonstra todas as funções principais do plugin.

0 commit comments

Comments
 (0)