You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/4/ptbr/part4b.md
+16-16Lines changed: 16 additions & 16 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -472,9 +472,9 @@ O código declara que a função atribuída a _main_ é assíncrona. Após isso,
472
472
473
473
### async/await in the backend
474
474
475
-
Let's start to change the backend to async and await. As all of the asynchronous operations are currently done inside of a function, it is enough to change the route handler functions into async functions.
475
+
Vamos começar a alterar o backend para usar async/await. Como todas as operações assíncronas atualmente são feitas dentro de uma função, basta mudar as funções que gerenciam a rota.
476
476
477
-
The route for fetching all notes gets changed to the following:
477
+
O código da rota para buscar todas as notas deve se alterado como segue:
We can verify that our refactoring was successful by testing the endpoint through the browser and by running the tests that we wrote earlier.
486
+
Podemos verificar que nosso refatoramento foi bem sucedido testando o endpoint pelo navegador e executando os testes que escrevemos mais cedo.
487
487
488
-
You can find the code for our current application in its entirety in the <i>part4-3</i> branch of [this GitHub repository](https://github.com/fullstack-hy2020/part3-notes-backend/tree/part4-3).
488
+
Você pode encontrar o código para da aplicação atual na branch da <i>part4-3</i> [nesse repositório GitHub](https://github.com/fullstack-hy2020/part3-notes-backend/tree/part4-3).
489
489
490
-
### More tests and refactoring the backend
490
+
### Mais testes e refatoração do backend
491
491
492
-
When code gets refactored, there is always the risk of [regression](https://en.wikipedia.org/wiki/Regression_testing), meaning that existing functionality may break. Let's refactor the remaining operations by first writing a test for each route of the API.
492
+
Quando o código é refatorado, sempre existe o risco de[regressão](https://pt.wikipedia.org/wiki/Teste_de_regress%C3%A3o), o que significa que funcionalidades existentes podem quebrar. Vamos refatorar as operações primeiramente restantes escrevendo um teste para cada rota da API.
493
493
494
-
Let's start with the operation for adding a new note. Let's write a test that adds a new note and verifies that the number of notes returned by the API increases and that the newly added note is in the list.
494
+
Vamos começar com a operação que adiciona uma nova nota. Vamos escrever um teste que adiciona uma nova nota e verifica que se o número de notas retornadas pela API aumenta e se a nova nota adicionada está na lista.
495
495
496
496
```js
497
497
test('a valid note can be added', async () => {
@@ -517,7 +517,7 @@ test('a valid note can be added', async () => {
517
517
})
518
518
```
519
519
520
-
Test fails since we are by accident returning the status code <i>200 OK</i> when a new note is created. Let us change that to <i>201 CREATED</i>:
520
+
O teste falha já que nós estamos acidentalmente retornando o códio de status <i>200 OK</i> quando uma nova nota é criada. Vamos mudar para <i>201 CRIADO(CREATED)</i>:
Let's also write a test that verifies that a note without content will not be saved into the database.
539
+
Vamos também escrever um teste que verifica que uma nota sem conteúdo não será salva no banco de dados.
540
540
541
541
```js
542
542
test('note without content is not added', async () => {
@@ -555,13 +555,13 @@ test('note without content is not added', async () => {
555
555
})
556
556
```
557
557
558
-
Both tests check the state stored in the database after the saving operation, by fetching all the notes of the application.
558
+
Ambos os testes checam o estado armazenado no banco de dados após a operação salvar, buscando todas as notas da aplicação.
559
559
560
560
```js
561
561
constresponse=awaitapi.get('/api/notes')
562
562
```
563
563
564
-
The same verification steps will repeat in other tests later on, and it is a good idea to extract these steps into helper functions. Let's add the function into a new file called <i>tests/test_helper.js</i> which is in the same directory as the test file.
564
+
Os mesmos passos de verificação serão repetidos posteriormente em outros testes, então é uma boa ideia extrair esses passos em uma função auxiliadora. Vamos adicionar a função em um novo arquivo chamado <i>tests/test_helper.js</i> que está no mesmo diretório do arquivo de teste.
565
565
566
566
```js
567
567
constNote=require('../models/note')
@@ -595,9 +595,9 @@ module.exports = {
595
595
}
596
596
```
597
597
598
-
The module defines the _notesInDb_function that can be used for checking the notes stored in the database. The _initialNotes_array containing the initial database state is also in the module. We also define the _nonExistingId_ function ahead of time, which can be used for creating a database object ID that does not belong to any note object in the database.
598
+
O módulo define a função _notesInDb_que pode ser utilizada para checar as notas armazenadas no banco de dados. O array _inicialNotes_ contendo o estado inicial do banco de dados também está no módulo. Além disso, definimos a futura função _noExistingId_. que pode ser utilizada para criar um objeto ID de banco de dados que não pertence a nenhum objeto nota no banco de dados.
599
599
600
-
Our tests can now use the helper module and be changed like this:
600
+
Nossos testes agora podem usar o módulo auxiliador (helper):
601
601
602
602
```js
603
603
constsupertest=require('supertest')
@@ -682,9 +682,9 @@ afterAll(async () => {
682
682
})
683
683
```
684
684
685
-
The code using promises works and the tests pass. We are ready to refactor our code to use the async/await syntax.
685
+
O código usando promessas funciona e os testes passam. Estamos prontos para refatorar nosso código para usar a sintaxe async/await
686
686
687
-
We make the following changes to the code that takes care of adding a new note(notice that the route handler definition is preceded by the _async_ keyword):
687
+
Nós fizemos as seguintes alterações no código que cuida de adicionar uma nova nota (note que a definição do gerenciador de rota está precedida pela palavra-chave _async_):
0 commit comments