# node-dto

> A small dto lib for nodejs

Latest version **2.0.2** (published 2024-07-17) · MIT license · 0 weekly downloads

## Install

```sh
npm install node-dto
pnpm add node-dto
yarn add node-dto
bun add node-dto
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.0.2 |
| Published | 2024-07-17 |
| First published | 2021-10-20 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 60.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Acidiney Dias |
| Maintainers | acidiney |
| Keywords | node-dto, dto, nodejs, javascript, data transfer object, node-package |

## Links

- npm: https://www.npmjs.com/package/node-dto
- Homepage: https://github.com/acidineydias/node-dto
- npm.io page: https://npm.io/package/node-dto

## Recent versions

- 2.0.2 (latest) — 2024-07-17
- 2.0.1 — 2024-07-17
- 2.0.0 — 2024-07-16
- 2.0.0-1 — 2024-07-16
- 2.0.0-0 — 2024-07-16
- 1.1.2 — 2024-06-28
- 1.1.1 — 2024-06-28
- 1.1.0 — 2021-10-24
- 1.0.9 — 2021-10-22
- 1.0.8 — 2021-10-21
- 1.0.6 — 2021-10-21
- 1.0.5 — 2021-10-21
- 1.0.4 — 2021-10-21
- 1.0.3 — 2021-10-21
- 1.0.2 — 2021-10-20
- … 2 more at https://npm.io/package/node-dto/versions

## README

# Node Dto
[![CodeQL](https://github.com/acidiney/node-dto/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/acidiney/node-dto/actions/workflows/codeql-analysis.yml)
<!-- [![Node.js Package](https://github.com/acidiney/node-dto/actions/workflows/npm-publish.yml/badge.svg)](https://github.com/acidiney/node-dto/actions/workflows/npm-publish.yml) -->
[![CircleCI](https://circleci.com/gh/acidiney/node-dto/tree/master.svg?style=svg)](https://circleci.com/gh/acidiney/node-dto/tree/master)
[![Coverage Status](https://coveralls.io/repos/github/acidiney/node-dto/badge.svg?branch=master)](https://coveralls.io/github/acidiney/node-dto?branch=master)

Node Dto is a small lib, that help developer to create dto's using javascript.

This package is focused only in javascript.

```bash
$ npm i node-dto
```

# How use

The `node-dto` package exports `MakeDto` function, that is a factory to generate your custom `Dto's`  and `TYPES` enum to help you find all available types to use

The `MakeDto` function receive an array of object with this schema:
```
{
  name: String,
  serialize: String,type: TYPES.STRING |
    TYPES.NUMBER |
    TYPES.DATE |
    TYPES.BOOLEAN |
    TYPES.OBJECT |
    TYPES.ENUM |
    TYPES.ARRAY,
  required: Boolean
}
```
Note: For type `Number` validator parses to Number Type in javascript check issue [Add Number Parsing for Number type](https://github.com/acidiney/node-dto/issues/6)

### Enum

For `Enum` type you need to pass a `enumOps` array props and specify, a list of accepted options.

Eg.

```js
MakeDto([
  {
    name: 'opsStatus',
    serialize: 'ops_status',
    required: true,
    type: TYPES.ENUM,
    enumOps: ['pending', 'approved', 'rejected']
  }
]
```

#### Object

For `Object` type you need to pass a `schema` array of object props. The `schema` prop follow the same interface that `MakeDto` exports.

Eg-

```js
MakeDto([
  {
    name: 'fields',
    serialize: 'fields',
    required: true,
    type: TYPES.OBJECT,
    schema: [
      {
        name: 'Name',
        serialize: 'name',
        required: true,
        type: 'Number',
      }
    ]
  }
]
```


#### Array

For `Array` type you need to pass a `itemsType` prop. The `itemsType` specify what will be type of `array` that will be validated.

In case of using `Enum` or `Object` you need to pass as well the `enumOps` or `schema` prop too.

Eg-

```js
MakeDto([
  {
    name: 'fields',
    serialize: 'fields',
    required: true,
    type: TYPES.ARRAY,
    itemsType: 'Number'
  }
]
```

or 


```js
MakeDto([
  {
    name: 'fields',
    serialize: 'fields',
    required: true,
    type: TYPES.ARRAY,
    itemsType: TYPES.ENUM,
    enumOps: ['accepted', 'nullable']
  }
]
```

or 

```js
MakeDto([
  {
    name: 'fields',
    serialize: 'fields',
    required: true,
    type: TYPES.ARRAY,
    itemsType: TYPES.OBJECT,
    schema: [
      {
        name: 'StatusCode',
        serialize: 'status_code',
        required: true,
        type: 'Number'
      }
    ]
  }
]
```

## Name

The `name` field is what key on object or array you will send. Eg. `{ fullName: 'Acidiney Dias' }`

## Serialize

The `serialize` field is the key the will be used to export after validate dto. Eg.  `{ full_name: 'Acidiney Dias' }`

## Type

As name said, the `type` field tell to dto internal function how to validate this field.

This help us, to skip unecessary `if` statemenet to check types.

Note: If you pass an invalid type, you will receive an `ValidateException`.

## Required

The `required` field, tell to dto internal function if can ignore when receive `null` in this field.

This prevents possible errors.

Eg. Receive an `null` on functions that calculate something.

# Available Methods

## .entries()

The `entries()` function returns all `name` keys wroted when Dto schema was created.

Eg:

```js

// CreateUserDto.js

const { MakeDto, TYPES } = require('node-dto')

module.exports = MakeDto([
  {
    name: 'firstName',
    serialize: 'first_name',
    required: true,
    type: TYPES.STRING
  },
  {
    name: 'lastName',
    serialize: 'last_name',
    required: true,
    type: TYPES.STRING
  },
  {
    name: 'email',
    serialize: 'email',
    required: true,
    type: TYPES.STRING
  }
])


// UserController.js

console.log(CreateUserDto.entries()) // firstName, lastName, email

```
You can use this, in `request.only` for example to retrive from request only this elements.

## .validate(obj: Object | array)

The `.validate` function receive the current payload, validate with type and obrigatority and returns an serialized `object` or throws an `ValidateException`.

Eg.

Dto:
```js

module.exports = MakeDto([
  {
    name: 'firstName',
    serialize: 'first_name',
    required: true,
    type: TYPES.STRING
  },
  {
    name: 'lastName',
    serialize: 'last_name',
    required: true,
    type: TYPES.STRING

  },
  {
    name: 'email',
    serialize: 'email',
    required: true,
    type: TYPES.STRING

  }
])

```

Comes:
```js

CreateUserDto.validate({
  firstName: 'Acidiney',
  lastName: 'Dias',
  email: 'acidineydias@gmail.com'
})

```

Returns:
```

{
  first_name: 'Acidiney',
  last_name: 'Dias',
  email: 'acidineydias@gmail.com'
}

```

Or an exception when something is wrong:

Comes:
```js

CreateUserDto.validate({
  firstName: 928292,
  lastName: 'Dias',
  email: 'acidineydias@gmail.com'
})

```

Returns:
```js

ValidateException: Field firstName with value 928292, is not valid!

```


## .validateAsync(obj: Object | array)

The `.validateAsync` function receive the current payload, validate with type and obrigatority and returns an serialized `object` or return `ValidationResult`.

Eg.

Dto:
```js

module.exports = MakeDto([
  {
    name: 'firstName',
    serialize: 'first_name',
    required: true,
    type: TYPES.STRING
  },
  {
    name: 'lastName',
    serialize: 'last_name',
    required: true,
    type: TYPES.STRING

  },
  {
    name: 'email',
    serialize: 'email',
    required: true,
    type: TYPES.STRING

  }
])

```

Comes:
```js

CreateUserDto.validateAsync({
  firstName: 'Acidiney',
  lastName: 'Dias',
  email: 'acidineydias@gmail.com'
})

```

Returns:
```

{
  success: true,
  value: {
    first_name: 'Acidiney',
    last_name: 'Dias',
    email: 'acidineydias@gmail.com'
  }
}

```

Or an exception when something is wrong:

Comes:
```js

CreateUserDto.validateAsync({
  firstName: 928292,
  lastName: 'Dias',
  email: 'acidineydias@gmail.com'
})

```

Returns:
```js
{
  success: false,
  value: [
    {
      first_name: 'INVALID_STRING_ERROR'
    }
  ]
}
```

## .export(data: Object | Array)

Sometimes you receive data from your database for exemple in one format like `snake_case` and you need tou transform to `camelCase`, in order to mantain your code more clean.

The `.export` function receives the untreated payload and returns a object using the fields `name` and `serialize` in your `Dto`.

Eg.

```js

module.exports = MakeDto([
  {
    name: 'firstName',
    serialize: 'first_name',
    required: true,
    type: TYPES.STRING

  },
  {
    name: 'lastName',
    serialize: 'last_name',
    required: true,
    type: TYPES.STRING

  },
  {
    name: 'email',
    serialize: 'email',
    required: true,
    type: TYPES.STRING

  }
])

```


Comes:
```js

CreateUserDto.export({
  first_name: 'Acidiney',
  last_name: 'Dias',
  email: 'acidineydias@gmail.com'
})

// or

CreateUserDto.export([
  {
  first_name: 'Acidiney',
  last_name: 'Dias',
  email: 'acidineydias@gmail.com'
},
{
  first_name: 'Jhon',
  last_name: 'Doe',
  email: 'jhon.doe@xyz.com'
}
])

```

Returns:
```
{
  firstName: 'Acidiney',
  lastName: 'Dias',
  email: 'acidineydias@gmail.com'
}

```

Or

```

[
  {
    firstName: 'Acidiney',
    lastName: 'Dias',
    email: 'acidineydias@gmail.com'
  },
  {
    firstName: 'Jhon',
    lastName: 'Doe',
    email: 'jhon.doe@xyz.com'
  }
]
```

## .exportUsingSQL(entity = null)

Sometimes using `.export` function can be slower, if you are using too much data.

In this case, you can use `.exportUsingSQL` function that consider your `Dto`, and returns an Array of `string`.

You can use this array in the `.select()` function of your ORM.

Eg. Using Knex

```js
  const users = await knex.from('users')
    .select(...Users.exportUsingSQL())
    .fetch();
```

Considering `join's` in queries you can pass the name of `entity` that this `Dto` belongs.


```js
  const users = await knex.from('tokens')
    .select('tokens.token', ...Users.exportUsingSQL('users'))
    .innerJoin('users', 'tokens.user_id', 'users.id')
    .fetch();
```

Feel free to submit an PR, to help project.

Thanks ^^

### Author

Acidiney Dias

---
_Source: https://npm.io/package/node-dto · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
