Coder Social home page Coder Social logo

node-dto's Introduction

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

node-dto's People

Contributors

acidiney avatar aj-ya avatar icyscools avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

node-dto's Issues

Suggest to add code formatter

Since this project seems to be more active and more contributors to contribute by.

I suggest adding a code formatter like Prettier to styling code.
And by using it, the code will be more readability and less conflict with the code since we'll use the same code styling format.

What do you think?

Add Object Type

This feat. allow us to create a schema that you want receive as a object. And the node-dto will understood this schema in order to validate an object entry.

Eg.

const objectSchemaDtoEg = MakeDto([
  {
    name: 'testObjSchema',
    type: 'Object',
    objSchema: [
      {
        name: 'Name',
        type: 'String',
        required: true,
        serialize: 'name'
      },
      {
        name: 'Age',
        type: 'Number',
        required: false,
        serialize: 'age'
      }
    ],
    required: true,
    serialize: 'test_obj_schema'
  }
])

This is a simple example. You can propose changes to this ideia.

Add defaultValue props

This props allow to node-dto returns a defaultValue on prop that is not required and receive a null.

This defaultValue need to be validated too.

Eg.

const exchangeRateDto = MakeDto([
  {
    name: 'exchangeRate',
    type: 'Number',
    required: false,
    defaultValue: 1,
    serialize: 'exchange_rate'
  }
])

exchangeRateDto.validate({
  exchangeRate: null
})

// shoud returns  -> { exchange_rate: 1 }

But

const exchangeRateDto = MakeDto([
  {
    name: 'exchangeRate',
    type: 'Number',
    required: false,
    defaultValue: 'F12x',
    serialize: 'exchange_rate'
  }
])

Should throws an ValidateError, because defaultValue is not of type Number.

Add Enum Type

The Enum type, receives an entry. And validate if current payload passed exists on Enum.

Eg.

const dto = MakeDto([
{
  name: 'status',
  serialize: 'status',
  type: 'Enum',
  enumOps: ['approved', 'pending', 'rejected'],
  required: true
}
])

// if user pass an option that not exists in enumOps, should throws an error

dto.validate({
  status: 'wait_something'
])

Add Array type

This feat. allow us to create an Dto that receives an Array of items.
When Dto is created, is required to define what is the type of items.

Eg.

  • Using Array of objects:
const objectSchemaDtoEg = MakeDto([
  {
    name: 'testArrayObjSchema',
    type: 'Array',
    itemsType: 'Object',
    objSchema: [
      {
        name: 'Name',
        type: 'String',
        required: true,
        serialize: 'name'
      },
      {
        name: 'Age',
        type: 'Number',
        required: false,
        serialize: 'age'
      }
    ],
    required: true,
    serialize: 'test_array_obj_schema'
  }
])
  • Using Array of numbers:
const objectSchemaDtoEg = MakeDto([
  {
    name: 'testArrayNumbersSchema',
    type: 'Array',
    itemsType: 'Number',
    required: true,
    serialize: 'test_array_numbers_schema'
  }
])

You can use this example to understood the propose of this issue

Accumulate Errors/Exceptions

when i pass 2 invalid field it throw exception with first error, but i think it should throw all error or exception accumulated

Validate number

When it validate number but revice 0 it throw exception.
But some i would use number 0.

validate = MakeDto([
  {
    name: 'order',
    serialize: 'order',
    type: 'Number',
    required: true,
  }
])

validate.validate({order: 0})

// throw Exception

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.