npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

node-dto

v2.0.2

Published

A small dto lib for nodejs

Downloads

143

Readme

Node Dto

CodeQL

CircleCI Coverage Status

Node Dto is a small lib, that help developer to create dto's using javascript.

This package is focused only in javascript.

$ 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

Enum

For Enum type you need to pass a enumOps array props and specify, a list of accepted options.

Eg.

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-

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-

MakeDto([
  {
    name: 'fields',
    serialize: 'fields',
    required: true,
    type: TYPES.ARRAY,
    itemsType: 'Number'
  }
]

or

MakeDto([
  {
    name: 'fields',
    serialize: 'fields',
    required: true,
    type: TYPES.ARRAY,
    itemsType: TYPES.ENUM,
    enumOps: ['accepted', 'nullable']
  }
]

or

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:


// 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:


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:


CreateUserDto.validate({
  firstName: 'Acidiney',
  lastName: 'Dias',
  email: '[email protected]'
})

Returns:


{
  first_name: 'Acidiney',
  last_name: 'Dias',
  email: '[email protected]'
}

Or an exception when something is wrong:

Comes:


CreateUserDto.validate({
  firstName: 928292,
  lastName: 'Dias',
  email: '[email protected]'
})

Returns:


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:


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:


CreateUserDto.validateAsync({
  firstName: 'Acidiney',
  lastName: 'Dias',
  email: '[email protected]'
})

Returns:


{
  success: true,
  value: {
    first_name: 'Acidiney',
    last_name: 'Dias',
    email: '[email protected]'
  }
}

Or an exception when something is wrong:

Comes:


CreateUserDto.validateAsync({
  firstName: 928292,
  lastName: 'Dias',
  email: '[email protected]'
})

Returns:

{
  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.


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:


CreateUserDto.export({
  first_name: 'Acidiney',
  last_name: 'Dias',
  email: '[email protected]'
})

// or

CreateUserDto.export([
  {
  first_name: 'Acidiney',
  last_name: 'Dias',
  email: '[email protected]'
},
{
  first_name: 'Jhon',
  last_name: 'Doe',
  email: '[email protected]'
}
])

Returns:

{
  firstName: 'Acidiney',
  lastName: 'Dias',
  email: '[email protected]'
}

Or


[
  {
    firstName: 'Acidiney',
    lastName: 'Dias',
    email: '[email protected]'
  },
  {
    firstName: 'Jhon',
    lastName: 'Doe',
    email: '[email protected]'
  }
]

.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

  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.

  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