aka-node-dto
v1.1.1
Published
A DTO for NodeJS which can be used in the node express framework.
Downloads
92
Maintainers
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.