Skip to content

Commit

Permalink
Merge pull request #26 from expressots/feature/dto-validator
Browse files Browse the repository at this point in the history
feat: add dto validator doc in en & pt-br
  • Loading branch information
rsaz authored Sep 13, 2023
2 parents a8f8782 + a5fbeca commit 97d4d62
Show file tree
Hide file tree
Showing 9 changed files with 227 additions and 13 deletions.
107 changes: 107 additions & 0 deletions docs/providers/dto-validator.md
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
6 changes: 3 additions & 3 deletions docs/providers/envvalidator.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
sidebar_position: 1
sidebar_position: 2
---

# Environment Validator
Expand All @@ -13,7 +13,7 @@ It is only included in the opinionated template or when you create a class that

You can find it in the `src/providers/application` folder in the opinionated template.

The `application.provider` is the main provider of the application that is responsible to control the **[Application Lifecycle](../overview/application.md#application-lifecycle-hooks)**.
The `application.provider` is the main provider of the application that is responsible to control the **[Application Lifecycle](../overview/application.md#application-lifecycle-hooks)**.

Inside of the Application class you can find three methods that are called in the following order:

Expand Down Expand Up @@ -46,4 +46,4 @@ ExpressoTS is an MIT-licensed open source project. It's an independent project w
- 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
- Share the project with your friends and colleagues
2 changes: 1 addition & 1 deletion docs/providers/in-memory-db.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
sidebar_position: 2
sidebar_position: 3
---

# In Memory DB
Expand Down
4 changes: 2 additions & 2 deletions docs/providers/prisma.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
sidebar_position: 2
sidebar_position: 4
---

# Prisma Provider
Expand All @@ -17,4 +17,4 @@ ExpressoTS is an MIT-licensed open source project. It's an independent project w
- 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
- Share the project with your friends and colleagues
2 changes: 1 addition & 1 deletion docusaurus.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ const config = {
},
announcementBar: {
id: "supportus",
content: "Current Version: v1.8.1",
content: "Current Version: v1.9.0",
backgroundColor: "#111",
textColor: "#19CE59",
isCloseable: false,
Expand Down
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
sidebar_position: 1
sidebar_position: 2
---

# Validator de ambiente
Expand All @@ -13,7 +13,7 @@ Ele está incluso apenas no modelo opinativo ou quando você cria uma classe que

Você pode encontrá-lo na pasta `src/providers/application` no modelo opinativo.

O `application.provider` é o provedor principal do aplicativo responsável por controlar o **[Application Lifecycle](../overview/application.md#application-lifecycle-hooks)**.
O `application.provider` é o provedor principal do aplicativo responsável por controlar o **[Application Lifecycle](../overview/application.md#application-lifecycle-hooks)**.

Dentro da classe Application você pode encontrar três métodos que são chamados na seguinte ordem:

Expand Down Expand Up @@ -46,4 +46,4 @@ ExpressoTS é um projeto de código aberto licenciado sob o MIT. É um projeto i
- 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
- Compartilhe o projeto com seus amigos e colegas
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
sidebar_position: 2
sidebar_position: 3
---

# BD em Memória
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
sidebar_position: 2
sidebar_position: 4
---

# Prisma provedor
Expand All @@ -17,4 +17,4 @@ ExpressoTS é um projeto de código aberto licenciado sob o MIT. É um projeto i
- 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
- Compartilhe o projeto com seus amigos e colegas

0 comments on commit 97d4d62

Please sign in to comment.