A simple plugin for class-transformer and class-validator which combines them in a nice and programmer-friendly API.
Installations
npm install class-transformer-validator
Score
94.6
Supply Chain
97.9
Quality
75.9
Maintenance
100
Vulnerability
99.6
License
Releases
Unable to fetch releases
Contributors
Developer
MichalLytek
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
14.3.0
NPM Version
6.14.5
Statistics
200 Stars
37 Commits
20 Forks
5 Watching
8 Branches
2 Contributors
Updated on 03 Jul 2024
Languages
TypeScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
10,025,956
Last day
-9.2%
9,410
Compared to previous day
Last week
-4%
50,858
Compared to previous week
Last month
14.4%
201,175
Compared to previous month
Last year
0.9%
2,589,704
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
class-transformer-validator
A simple plugin for class-transformer and class-validator which combines them in a nice and programmer-friendly API.
Installation
Module installation
npm install class-transformer-validator --save
(or the short way):
npm i -S class-transformer-validator
Peer dependencies
This package is only a simple plugin/wrapper, so you have to install the required modules too because it can't work without them. See detailed installation instruction for the modules installation:
Usage
The usage of this module is very simple.
1import { IsEmail } from "class-validator"; 2import { transformAndValidate } from "class-transformer-validator"; 3 4// declare the class using class-validator decorators 5class User { 6 @IsEmail() 7 public email: string; 8 9 public hello(): string { 10 return "World!"; 11 } 12} 13 14// then load the JSON string from any part of your app 15const userJson: string = loadJsonFromSomething(); 16 17// transform the JSON to class instance and validate it correctness 18transformAndValidate(User, userJson) 19 .then((userObject: User) => { 20 // now you can access all your class prototype method 21 console.log(`Hello ${userObject.hello()}`); // prints "Hello World!" on console 22 }) 23 .catch(err => { 24 // here you can handle error on transformation (invalid JSON) 25 // or validation error (e.g. invalid email property) 26 console.error(err); 27 });
You can also transform and validate plain JS object (e.g. from express req.body). Using ES7 async/await syntax:
1async (req, res) => { 2 try { 3 // transform and validate request body 4 const userObject = await transformAndValidate(User, req.body); 5 // infered type of userObject is User, you can access all class prototype properties and methods 6 } catch (err) { 7 // your error handling 8 console.error(err); 9 } 10};
And since release 0.3.0
you can also pass array of objects - all of them will be validated using given class validation constraints:
1async (req, res) => {
2 try {
3 // transform and validate request body - array of User objects
4 const userObjects = await transformAndValidate(User, req.body);
5 userObjects.forEach(user => console.log(`Hello ${user.hello()}`));
6 } catch (err) {
7 // your error handling
8 }
9};
API reference
Function signatures
There is available the transformAndValidate
function with three overloads:
1function transformAndValidate<T extends object>( 2 classType: ClassType<T>, 3 jsonString: string, 4 options?: TransformValidationOptions, 5): Promise<T | T[]>;
1function transformAndValidate<T extends object>( 2 classType: ClassType<T>, 3 object: object, 4 options?: TransformValidationOptions, 5): Promise<T>;
1function transformAndValidate<T extends object>( 2 classType: ClassType<T>, 3 array: object[], 4 options?: TransformValidationOptions, 5): Promise<T[]>;
Be aware that if you validate json string, the return type is a Promise
of T
or T[]
so you need to assert the returned type if you know the shape of json:
1const users = (await transformAndValidate( 2 User, 3 JSON.stringify([{ email: "test@test.test" }]), 4)) as User[];
Or you can just check the type in runtime using Array.isArray
method.
Synchronous transformation and validation
If you need sync validation, use transformAndValidateSync
function instead (available since v0.4.0). It will synchronously return T
or T[]
, not a Promise.
Parameters and types
classType
- an class symbol, a constructor function which can be called withnew
1type ClassType<T> = { 2 new (...args: any[]): T; 3};
-
jsonString
- a normal string containing JSON -
object
- plain JS object of typeobject
(introduced in TypeScript 2.2), you will have compile-time error while trying to pass number, boolean, null or undefined but unfortunately run-time error when passing a function -
array
- array of plain JS objects like described above -
options
- optional options object, it has two optional properties
1interface TransformValidationOptions { 2 validator?: ValidatorOptions; 3 transformer?: ClassTransformOptions; 4}
You can use it to pass options for class-validator
(more info) and for class-transformer
(more info).
More info
The class-transformer and class-validator are more powerful than it was showed in the simple usage sample, so go to their github page and check out they capabilities!
Release notes
0.9.1
- widen
class-transformer
peer dependency version range to>=0.2.3
- updated all dev dependencies
0.9.0
- bump
class-validator
peer dependency to version>=0.12.0
- updated TypeScript dependency to version
^3.9.5
- updated all dev dependencies
0.8.0
- updated
class-transformer
dependency to version^0.2.3
- updated
class-validator
dependency to version^0.10.1
- updated TypeScript dependency to version
^3.6.3
- built code is now emitted as ES2015 (dropped es5 support)
- updated all dev dependencies
0.7.1
- updated
class-transformer
dependency to version^0.2.0
0.6.0
- updated
class-validator
dependency to version^0.9.1
0.5.0
- remove deprecated
TransformValdiationOptions
interface (typo) - updated
class-validator
dependency to version^0.8.1
andclass-transformer
to^0.1.9
0.4.1
- fix
TransformValdiationOptions
interface name typo (deprecate in favour ofTransformValidationOptions
)
0.4.0
- added
transformAndValidateSync
function for synchronous validation - changed return type for JSON's transform and validation to
Promise
ofT
orT[]
- updated
class-validator
dependency to version^0.7.2
andclass-transformer
to^0.1.7
0.3.0
- added support for transform and validate array of objects given class
- updated
class-validator
dependency to version^0.7.1
0.2.0
- changed object parameter type declaration to
object
(introduced in TS 2.2) - throwing error when passed array, undefined or null
0.1.1
- changed throwing error (rejecting promise) from string to
Error
with message
0.1.0
- initial version with
transformAndValidate
function
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 2/28 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 5 are checked with a SAST tool
Reason
19 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-fj58-h2fr-3pp2
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-2j2x-2gpw-g8fm
- Warn: Project is vulnerable to: GHSA-4q6p-r6v2-jvc5
- Warn: Project is vulnerable to: GHSA-ww39-953v-wcq6
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-xvch-5gv4-984h
- Warn: Project is vulnerable to: GHSA-hj48-42vr-x3v9
- Warn: Project is vulnerable to: GHSA-g6ww-v8xp-vmwg
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-44c6-4v22-4mhx
- Warn: Project is vulnerable to: GHSA-4x5v-gmq8-25ch
- Warn: Project is vulnerable to: GHSA-qgmg-gppg-76g5
- Warn: Project is vulnerable to: GHSA-xx4c-jj58-r7x6
- Warn: Project is vulnerable to: GHSA-c4w7-xm78-47vh
Score
1.7
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More