-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #26 from expressots/feature/dto-validator
feat: add dto validator doc in en & pt-br
- Loading branch information
Showing
9 changed files
with
227 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
--- | ||
sidebar_position: 1 | ||
--- | ||
|
||
# DTO Validator | ||
|
||
The DTO Validator provider is a provider that ExpressoTS offers out-of-the-box. It is used to validate the incoming data from the client. It helps the developer to avoid runtime errors caused by missing or invalid data. | ||
|
||
When you scaffold a new project, the DTO Validator provider is already included as a middleware that can be used in any endpoint. The middleware is called `validateDTO`. | ||
|
||
## Pre Requisites | ||
|
||
The DTO validator is based on the [class-validator](https://www.npmjs.com/package/class-validator) and [class-transformer](https://www.npmjs.com/package/class-transformer) packages. It uses decorators to validate the DTOs. | ||
|
||
:::tip | ||
If you don't have class-validator and class-transformer installed and try to use the DTO validator, you will get an warning message in the console mentioning that you need to install the packages. | ||
::: | ||
|
||
Another important thing to mention is that the DTO validator works only with classes, as interfaces doesn't exist in runtime. So, if you want to use the DTO validator, you need to create a class that represents your DTO rather than the current interface provided by ExpressoTS. | ||
|
||
## How To Use | ||
|
||
You can use the DTO validator in any endpoint by adding the `validateDTO` middleware in the endpoint route. | ||
|
||
Endpoint that creates a new user: | ||
|
||
```typescript | ||
@httpPost("/", ValidateDTO(CreateUserDTO)) | ||
execute(@requestBody() payload: CreateUserDTO, @response() res: Response) { | ||
return res.status(StatusCode.Created).json(this.createUserUseCase.execute(payload)); | ||
} | ||
``` | ||
|
||
Here it is the `CreateUserDTO` class: | ||
|
||
```typescript | ||
import { IsEmail, IsNotEmpty, MinLength } from "class-validator"; | ||
|
||
class CreateUserDTO { | ||
@IsNotEmpty() | ||
@MinLength(10) | ||
name: string; | ||
@IsNotEmpty() | ||
@IsEmail({}, { message: "Invalid email" }) | ||
email: string; | ||
} | ||
|
||
export { CreateUserDTO }; | ||
``` | ||
|
||
:::info | ||
For more information about the decorators, please check the [class-validator](https://www.npmjs.com/package/class-validator) package. | ||
::: | ||
|
||
## DTO Validator Error Messages | ||
|
||
If you submit a payload that doesn't match the DTO `CreateUserDTO` above, the DTO validator will return an error message with the following format: | ||
|
||
**Payload:** | ||
|
||
```json | ||
{ | ||
"name": "", | ||
"email": "" | ||
} | ||
``` | ||
|
||
**Response:** | ||
|
||
```json | ||
{ | ||
"errorCode": 400, | ||
"errorMessage": "Bad Request", | ||
"DTO": [ | ||
{ | ||
"property": "name", | ||
"messages": [ | ||
"name must be longer than or equal to 10 characters", | ||
"name should not be empty" | ||
] | ||
}, | ||
{ | ||
"property": "email", | ||
"messages": ["invalid email", "email should not be empty"] | ||
} | ||
] | ||
} | ||
``` | ||
|
||
Messages are split by property, so you can easily identify which property has an error and what is the error message. This is useful when you have a DTO with a lot of properties, as you can easily identify which property has an error. It also helps the frontend application on getting the error messages more easily. | ||
|
||
:::caution SPOILER ALERT | ||
The ValidateDTO is part of the functionalities that ExpressoTS offers out-of-the-box to help you to build your application faster. In the next versions of ExpressoTS for every functionality that ExpressoTS offers out-of-the-box, we will provide a way for you to customize it or use your own implementation based on your favorite package or library. | ||
::: | ||
|
||
--- | ||
|
||
## Support the Project | ||
|
||
ExpressoTS is an MIT-licensed open source project. It's an independent project with ongoing development made possible thanks to your support. If you'd like to help, please consider: | ||
|
||
- Become a **[sponsor on GitHub](https://github.com/sponsors/expressots)** | ||
- Follow the **[organization](https://github.com/expressots)** on GitHub and Star ⭐ the project | ||
- Subscribe to the Twitch channel: **[Richard Zampieri](https://www.twitch.tv/richardzampieri)** | ||
- Join our **[Discord](https://discord.com/invite/PyPJfGK)** | ||
- Contribute submitting **[issues and pull requests](https://github.com/expressots/expressots/issues/new/choose)** | ||
- Share the project with your friends and colleagues |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,5 @@ | ||
--- | ||
sidebar_position: 2 | ||
sidebar_position: 3 | ||
--- | ||
|
||
# In Memory DB | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletions
107
i18n/pt/docusaurus-plugin-content-docs/current/providers/dto-validator.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
--- | ||
sidebar_position: 1 | ||
--- | ||
|
||
# Validador de DTO | ||
|
||
O provedor Validador de DTO é um recurso que o ExpressoTS oferece nativamente. É usado para validar os dados vindos do cliente. Ajuda o desenvolvedor a evitar erros em tempo de execução causados por dados faltantes ou inválidos. | ||
|
||
Quando você cria um novo projeto, o provedor Validador de DTO já vem incluído como um middleware que pode ser usado em qualquer endpoint. O middleware é chamado `validateDTO`. | ||
|
||
## Pré-requisitos | ||
|
||
O validador de DTO é baseado nos pacotes class-validator e class-transformer. Utiliza decoradores para validar os DTOs. | ||
|
||
:::tip | ||
Se você não tiver [class-validator](https://www.npmjs.com/package/class-validator) e [class-transformer](https://www.npmjs.com/package/class-transformer) instalados e tentar usar o validador de DTO, você receberá uma mensagem de aviso no console indicando que você precisa instalar os pacotes. | ||
::: | ||
|
||
Outra coisa importante a mencionar é que o validador de DTO funciona apenas com classes, já que interfaces não existem em tempo de execução. Portanto, se você deseja usar o validador de DTO, você precisa criar uma classe que represente seu DTO em vez da interface atual fornecida pelo ExpressoTS. | ||
|
||
## Como Usar | ||
|
||
Você pode usar o validador de DTO em qualquer endpoint, adicionando o middleware validateDTO na rota do endpoint. | ||
|
||
Endpoint que cria um novo usuário: | ||
|
||
```typescript | ||
@httpPost("/", ValidateDTO(CreateUserDTO)) | ||
execute(@requestBody() payload: CreateUserDTO, @response() res: Response) { | ||
return res.status(StatusCode.Created).json(this.createUserUseCase.execute(payload)); | ||
} | ||
``` | ||
|
||
Aqui está a classe `CreateUserDTO`: | ||
|
||
```typescript | ||
import { IsEmail, IsNotEmpty, MinLength } from "class-validator"; | ||
|
||
class CreateUserDTO { | ||
@IsNotEmpty() | ||
@MinLength(10) | ||
name: string; | ||
@IsNotEmpty() | ||
@IsEmail({}, { message: "Invalid email" }) | ||
email: string; | ||
} | ||
|
||
export { CreateUserDTO }; | ||
``` | ||
|
||
:::info | ||
Para mais informações sobre os decoradores, consulte o pacote [class-validator](https://www.npmjs.com/package/class-validator). | ||
::: | ||
|
||
## Mensagens de Erro do Validador de DTO | ||
|
||
Se você enviar um payload que não corresponde ao DTO CreateUserDTO acima, o validador de DTO retornará uma mensagem de erro com o seguinte formato: | ||
|
||
**Payload:** | ||
|
||
```json | ||
{ | ||
"name": "", | ||
"email": "" | ||
} | ||
``` | ||
|
||
**Resposta:** | ||
|
||
```json | ||
{ | ||
"errorCode": 400, | ||
"errorMessage": "Bad Request", | ||
"DTO": [ | ||
{ | ||
"property": "name", | ||
"messages": [ | ||
"name must be longer than or equal to 10 characters", | ||
"name should not be empty" | ||
] | ||
}, | ||
{ | ||
"property": "email", | ||
"messages": ["invalid email", "email should not be empty"] | ||
} | ||
] | ||
} | ||
``` | ||
|
||
As mensagens são divididas por propriedade, facilitando a identificação de qual propriedade tem um erro e qual é a mensagem de erro. Isso é útil quando você tem um DTO com muitas propriedades, pois permite identificar facilmente qual propriedade tem um erro. Também ajuda a aplicação frontend a receber as mensagens de erro de forma mais fácil. | ||
|
||
:::caution ALERTA DE SPOILER | ||
O ValidateDTO faz parte das funcionalidades que o ExpressoTS oferece nativamente para ajudá-lo a construir sua aplicação mais rapidamente. Nas próximas versões do ExpressoTS para cada funcionalidade que o ExpressoTS oferece nativamente, forneceremos uma maneira de você personalizá-la ou usar sua própria implementação baseada em seu pacote ou biblioteca favorita. | ||
::: | ||
|
||
--- | ||
|
||
## Apoie o projeto | ||
|
||
ExpressoTS é um projeto de código aberto licenciado sob o MIT. É um projeto independente com desenvolvimento contínuo possibilitado graças ao seu suporte. Se você deseja ajudar, por favor considere: | ||
|
||
- Se tornar um **[Sponsor no GitHub](https://github.com/sponsors/expressots)** | ||
- Siga a **[organização](https://github.com/expressots)** no GitHub e de um Star ⭐ no projeto | ||
- Subscreva no nosso canal na Twitch: **[Richard Zampieri](https://www.twitch.tv/richardzampieri)** | ||
- Entre no nosso **[Discord](https://discord.com/invite/PyPJfGK)** | ||
- Contribua submetendo **[issues e pull requests](https://github.com/expressots/expressots/issues/new/choose)** | ||
- Compartilhe o projeto com seus amigos e colegas |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
i18n/pt/docusaurus-plugin-content-docs/current/providers/in-memory-db.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,5 @@ | ||
--- | ||
sidebar_position: 2 | ||
sidebar_position: 3 | ||
--- | ||
|
||
# BD em Memória | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters