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

aka-node-dto

v1.1.1

Published

A DTO for NodeJS which can be used in the node express framework.

Downloads

92

Readme

aka-node-dto

A DTO for parsing and validating the data object in NodeJS application.
Could be use with any project server or normal application.
This helps in validating the object with the model definer. This is similar to mongoose mondel and validations are derived from the angular like structure.

Import the Module

const {makeDTO} = require('aka-node-dto');

Create the DTO

const {makeDTO} = require('aka-node-dto');

// Create the DTO
const People = makeDTO({
    name: {
        type: String,
        required: true
    },
    age: {
        type: String,
        default: 0
    },
    date_of_birth: {
        type: Date,
        format: "date"
    }
});

// Create an instance of the dto for parsing the data
const inputdata = {
    name: "John Doe",
    age: 25,
    date_of_birth: "1994-07-15"
};

const people = new People(inputdata);

// Now build the data for the parsing of data through DTO validation layer
const resulteddata = people.build();

Different types that can be used in the field type

  • String :- Use to denote that the type of a field is string value.
  • Number :- Use to denote any number type.
  • Boolean :- Denote to use the bool value.
  • Date :- Denote to mark the field as the date type. Note in the json object the type will be string, but the format of the value must be a valid date format.
    Ex:- Date: 2024-09-10 | TimeStamp: 2024-09-10 12:02:00 | only Time: 15:20:00
  • DTO :- Use to denote a nested object. Mark a field which will contains anoter object model, which can be mark as a reference of DTO.
    Below is the example of using the DTO as a type.

Create the DTO with nested object

const {makeDTO} = require('aka-node-dto');

// Address DTO
const Address = makeDTO({
  address_line1: {
    type: String
  },
  city: {
    type: String,
    required: true,
  },
  state: {
    type: String,
    required: true,
  },
  zipcode: {
    type: String,
    required: true,,
    length: 7 // Max 7 length
  },
  country: {
    type: String,
    required: true,    
  },
})

// Create the DTO
const People = makeDTO({
    name: {
        type: String,
        required: true
    },
    age: {
        type: String,
        default: 0
    },
    date_of_birth: {
        type: Date,
        format: "date"
    },
    address: {
      type: Address,
      required: true
    }
});

// Create an instance of the dto for parsing the data
const inputdata = {
    name: "John Doe",
    age: 25,
    date_of_birth: "1994-07-15",
    address: {
      address_line1: "New Yourk",
      city: "New York",
      // Rest of the address fields
    }
};

const people = new People(inputdata);

// Now build the data for the parsing of data through DTO validation layer
const resulteddata = people.build();

Introducing Arrays

  // Create an address dto
  const Address = makeDTO({
      city: {
        type: String
      },
      country: {
        type: String
      }
  });
  // A User dto
  const User = makeDTO({
      name: { 
          type: String 
      },
      // An User can have multiple address saved
      address: { 
          type: Array, // Note the Type
          arrayDataType: Address // The arrayDataType field is required. What type of value does your array contains this will define that. This will hold the same type of value as of type field.
      }
  });

  const inputData = {
    name: "John Doe",
    address: [
      {
        "city": "Kolkata",
        "country": "India"
      }
    ]
  };

  const evaludatedData = userData.build();
  console.log(evaludatedData);

Output

{
  name: "John Doe",
    address: [
      {
        "city": "Kolkata",
        "country": "India"
      }
    ]
}

Create the DTO with Validation

const {makeDTO, Validators} = require('aka-node-dto');

// Create the DTO
const People = makeDTO({
    name: {
        type: String,
        required: true // This will mark the field as required
    },
    age: {
        type: String,
        default: 0,
        validators: [
          Validators.required, // Another way of marking a field required
          Validators.max(25) // This will mark the field with a limit
        ]
    },
    date_of_birth: {
        type: Date,
        format: "date"
    }
});

// Create an instance of the dto for parsing the data
const inputdata = {
    name: "John Doe",
    age: 25,
    date_of_birth: "1994-07-15"
};

const people = new People(inputdata);

// Now build the data for the parsing of data through DTO validation layer
const resulteddata = people.build();

Below are the different validators you can use with the DTO

Validators Library

This library provides a set of validation functions for validating form fields. It can be used to ensure that data entered by users conforms to specific criteria like required fields, length limits, value ranges, and specific formats (email, phone, etc.). Additionally, custom validators can be created for more complex validation logic.

Installation

To install this library, use npm:

npm install aka-node-dto

Usage

Importing Validators

const {Validators} = require('aka-node-dto');

Available Validators

1. required: ValidatorFunction

Ensures that the field value is provided. Throws an error if the field is empty or undefined.

Validators.required;

2. minLength(length: number): ValidatorFunction

Validates that the length of the field's value is greater than or equal to the specified length.

Validators.minLength(5);

3. maxLength(length: number): ValidatorFunction

Validates that the length of the field's value is less than or equal to the specified length.

Validators.maxLength(20);

4. min(minValue: number): ValidatorFunction

Checks if the field's value is a number and greater than or equal to the specified minValue.

Validators.min(10);

5. max(maxValue: number): ValidatorFunction

Checks if the field's value is a number and less than or equal to the specified maxValue.

Validators.max(100);

6. isEmail: ValidatorFunction

Validates that the field's value is in a valid email format. This checks the structure of the email but does not guarantee its authenticity.

Validators.isEmail;

7. isPhone: ValidatorFunction

Validates that the field's value is a valid phone number format. This checks the structure but not the genuineness of the phone number.

Validators.isPhone;

8. isNumber: ValidatorFunction

Ensures that the field's value is a valid number.

Validators.isNumber;

9. isBoolean: ValidatorFunction

Validates that the field's value is a boolean (true or false).

Validators.isBoolean;

10. isString: ValidatorFunction

Validates that the field's value is a string.

Validators.isString;

11. isEnum(enumType: {[key:string]: string | number} | Array<string | number>): ValidatorFunction

Checks whether the field's value is one of the defined enum values (either as an object or an array).

Validators.isEnum({ ACTIVE: 'active', INACTIVE: 'inactive' });
// or
Validators.isEnum(['active', 'inactive']);

12. maxDateTime(date: Date | string, compareType: "date" | "time" | "timestamp"): ValidatorFunction

Validates that the field's value does not exceed the specified date and compareType. Only applicable to fields of type Date.

Validators.maxDateTime(new Date(), 'date');

13. minDateTime(date: Date | string, compareType: "date" | "time" | "timestamp"): ValidatorFunction

Validates that the field's value is greater than or equal to the specified date and compareType. Only applicable to fields of type Date.

Validators.minDateTime('2023-01-01', 'timestamp');

14. custom(validateFn: (name: string, key: string, value: any, config: FieldConfig) => void): ValidatorFunction

Allows you to create custom validation logic. The function validateFn takes the field's name, key, value, and configuration (config) as parameters and performs validation.

Validators.custom((name, key, value, config) => {
  if (value !== 'validValue') {
    throw new Error(`${name} must have a valid value`);
  }
});

Example Usage

import Validators from '@your-organization/validators';

// Define your field configuration
const fieldConfig = {
  fieldName: 'username',
  value: 'john_doe',
  validations: [
    Validators.required,
    Validators.minLength(5),
    Validators.maxLength(20),
    Validators.isString
  ]
};

// Run validations
fieldConfig.validations.forEach((validator) => {
  validator('username', 'username', fieldConfig.value, fieldConfig);
});

License

This project is licensed under the MIT License.