├── .editorconfig ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── code-of-conduct.md ├── package-lock.json ├── package.json ├── rollup.config.ts ├── src ├── lib.ts └── typescript-param-validator.ts ├── test └── typescript-param-validator.test.ts ├── tools ├── gh-pages-publish.ts └── semantic-release-prepare.ts ├── tsconfig.json └── tslint.json /.editorconfig: -------------------------------------------------------------------------------- 1 | #root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | max_line_length = 100 10 | indent_size = 2 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | .nyc_output 4 | .DS_Store 5 | *.log 6 | .vscode 7 | .idea 8 | dist 9 | compiled 10 | .awcache 11 | .rpt2_cache 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | branches: 3 | only: 4 | - master 5 | - /^greenkeeper/.*$/ 6 | cache: 7 | yarn: true 8 | directories: 9 | - node_modules 10 | notifications: 11 | email: false 12 | node_js: 13 | - node 14 | script: 15 | - npm run test:prod && npm run build 16 | after_success: 17 | - npm run report-coverage 18 | - npm run deploy-docs 19 | - npm run semantic-release 20 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | We're really glad you're reading this, because we need volunteer developers to help this project come to fruition. 👏 2 | 3 | ## Instructions 4 | 5 | These steps will guide you through contributing to this project: 6 | 7 | - Fork the repo 8 | - Clone it and install dependencies 9 | 10 | git clone https://github.com/YOUR-USERNAME/typescript-library-starter 11 | npm install 12 | 13 | Keep in mind that after running `npm install` the git repo is reset. So a good way to cope with this is to have a copy of the folder to push the changes, and the other to try them. 14 | 15 | Make and commit your changes. Make sure the commands npm run build and npm run test:prod are working. 16 | 17 | Finally send a [GitHub Pull Request](https://github.com/alexjoverm/typescript-library-starter/compare?expand=1) with a clear list of what you've done (read more [about pull requests](https://help.github.com/articles/about-pull-requests/)). Make sure all of your commits are atomic (one feature per commit). 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 Dima Grossman 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Typescript runtime param validation 2 | 3 | A library for runtime param validations using typescript decorators 4 | that works with `class-validator` library. 5 | 6 | Useful when you need to validate parameter data coming from untyped source(i.e http body, and etc...) or when you need to perform complex validations on the input params. 7 | 8 | Using the param validation decorator you can declare your validation on the type annotation and leave the validation work to `class-validator` 9 | 10 | ## Install 11 | ```bash 12 | npm install --save typescript-param-validator class-validators 13 | ``` 14 | 15 | ## Examples 16 | ```typescript 17 | import { Validator, Validate } from 'typescript-param-validator'; 18 | import { IsDate, IsNotEmpty, MaxDate, IsEmail, Length } from 'class-validators'; 19 | 20 | class DataDto { 21 | @IsNotEmpty() 22 | @IsEmail() 23 | email: string; 24 | 25 | @Length(10, 200) 26 | @IsNotEmpty() 27 | description: string; 28 | 29 | @IsDate() 30 | @IsNotEmpty() 31 | @MaxDate(new Date()) 32 | birthDate: Date; 33 | } 34 | 35 | class TestClass { 36 | @Validate() 37 | methodName(@Validator() data: DataDto) { 38 | 39 | } 40 | 41 | @Validate() 42 | serverControllerEndpoint(@Validator(DataDto, 'body') req: Request) { 43 | 44 | } 45 | } 46 | 47 | const instance = new TestClass(); 48 | 49 | // Will throw class-validator errors on runtime 50 | instance.methodName({ 51 | birthDate: new Date(), 52 | description: '123', 53 | email: 'fakemail' 54 | }); 55 | 56 | instance.serverControllerEndpoint({ 57 | body: { 58 | birthDate: new Date(), 59 | description: '123', 60 | email: 'fakemail' 61 | } 62 | }); 63 | ``` 64 | 65 | ### Catching the Validation errors 66 | 67 | In order to catch the validation errors you need to check if the errors is instanceof `ValidatorError`; 68 | 69 | ```typescript 70 | import { ValidatorError } from 'typescript-param-validator'; 71 | 72 | try { 73 | // ... code 74 | } catch (error) { 75 | if (error instanceof ValidatorError) { 76 | // here you have access to the validationErrors object that 77 | // will contain array of `class-validator` error objects. 78 | console.log(error.validationErrors); 79 | } 80 | } 81 | ``` 82 | 83 | -------------------------------------------------------------------------------- /code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at alexjovermorales@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typescript-param-validator", 3 | "version": "0.1.0", 4 | "description": "", 5 | "keywords": [], 6 | "main": "dist/typescript-param-validator.umd.js", 7 | "module": "dist/typescript-param-validator.es5.js", 8 | "typings": "dist/types/typescript-param-validator.d.ts", 9 | "files": [ 10 | "dist" 11 | ], 12 | "author": "Dima Grossman ", 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/scopsy/typescript-param-validator" 16 | }, 17 | "license": "MIT", 18 | "engines": { 19 | "node": ">=6.0.0" 20 | }, 21 | "scripts": { 22 | "lint": "tslint -t codeFrame 'src/**/*.ts' 'test/**/*.ts'", 23 | "prebuild": "rimraf dist", 24 | "build": "tsc --module commonjs --outDir dist/lib && rollup -c rollup.config.ts && typedoc --out dist/docs --target es6 --theme minimal --mode file src", 25 | "start": "rollup -c rollup.config.ts -w", 26 | "test": "jest", 27 | "test:watch": "jest --watch", 28 | "test:prod": "npm run lint && npm run test -- --coverage --no-cache", 29 | "deploy-docs": "ts-node tools/gh-pages-publish", 30 | "report-coverage": "cat ./coverage/lcov.info | coveralls", 31 | "commit": "git-cz", 32 | "semantic-release": "semantic-release", 33 | "semantic-release-prepare": "ts-node tools/semantic-release-prepare", 34 | "precommit": "lint-staged", 35 | "travis-deploy-once": "travis-deploy-once", 36 | "prepush": "npm run test:prod && npm run build", 37 | "commitmsg": "validate-commit-msg" 38 | }, 39 | "lint-staged": { 40 | "{src,test}/**/*.ts": [ 41 | "prettier --write --single-quote --print-width 120", 42 | "git add" 43 | ] 44 | }, 45 | "config": { 46 | "commitizen": { 47 | "path": "node_modules/cz-conventional-changelog" 48 | }, 49 | "validate-commit-msg": { 50 | "types": "conventional-commit-types", 51 | "helpMessage": "Use \"npm run commit\" instead, we use conventional-changelog format :) (https://github.com/commitizen/cz-cli)" 52 | } 53 | }, 54 | "jest": { 55 | "transform": { 56 | ".(ts|tsx)": "/node_modules/ts-jest/preprocessor.js" 57 | }, 58 | "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", 59 | "moduleFileExtensions": [ 60 | "ts", 61 | "tsx", 62 | "js" 63 | ], 64 | "coveragePathIgnorePatterns": [ 65 | "/node_modules/", 66 | "/test/" 67 | ], 68 | "coverageThreshold": { 69 | "global": { 70 | "branches": 90, 71 | "functions": 95, 72 | "lines": 95, 73 | "statements": 95 74 | } 75 | }, 76 | "collectCoverage": true, 77 | "mapCoverage": true 78 | }, 79 | "devDependencies": { 80 | "@types/jest": "^22.0.0", 81 | "@types/node": "^8.0.0", 82 | "colors": "^1.1.2", 83 | "commitizen": "^2.9.6", 84 | "coveralls": "^3.0.0", 85 | "cross-env": "^5.0.1", 86 | "cz-conventional-changelog": "^2.0.0", 87 | "husky": "^0.14.0", 88 | "jest": "^22.0.2", 89 | "lint-staged": "^6.0.0", 90 | "lodash.camelcase": "^4.3.0", 91 | "prettier": "^1.4.4", 92 | "prompt": "^1.0.0", 93 | "replace-in-file": "^3.0.0-beta.2", 94 | "rimraf": "^2.6.1", 95 | "rollup": "^0.53.0", 96 | "rollup-plugin-commonjs": "^8.0.2", 97 | "rollup-plugin-node-resolve": "^3.0.0", 98 | "rollup-plugin-sourcemaps": "^0.4.2", 99 | "rollup-plugin-typescript2": "^0.9.0", 100 | "semantic-release": "^12.2.2", 101 | "ts-jest": "^22.0.0", 102 | "ts-node": "^4.1.0", 103 | "tslint": "^5.8.0", 104 | "tslint-config-prettier": "^1.1.0", 105 | "tslint-config-standard": "^7.0.0", 106 | "typedoc": "^0.9.0", 107 | "typescript": "^2.6.2", 108 | "validate-commit-msg": "^2.12.2", 109 | "travis-deploy-once": "^4.3.1" 110 | }, 111 | "dependencies": { 112 | "reflect-metadata": "^0.1.12", 113 | "class-validator": "^0.7.3", 114 | "class-transformer": "^0.1.8" 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /rollup.config.ts: -------------------------------------------------------------------------------- 1 | import resolve from 'rollup-plugin-node-resolve'; 2 | import commonjs from 'rollup-plugin-commonjs'; 3 | import sourceMaps from 'rollup-plugin-sourcemaps'; 4 | import camelCase from 'lodash.camelcase'; 5 | import typescript from 'rollup-plugin-typescript2'; 6 | 7 | const pkg = require('./package.json'); 8 | 9 | const libraryName = 'typescript-param-validator'; 10 | 11 | export default { 12 | input: `src/${libraryName}.ts`, 13 | output: [ 14 | { file: pkg.main, name: camelCase(libraryName), format: 'umd' }, 15 | { file: pkg.module, format: 'es' }, 16 | ], 17 | sourcemap: true, 18 | // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash') 19 | external: [], 20 | watch: { 21 | include: 'src/**', 22 | }, 23 | plugins: [ 24 | // Compile TypeScript files 25 | typescript(), 26 | // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs) 27 | commonjs(), 28 | // Allow node_modules resolution, so you can use 'external' to control 29 | // which external modules to include in the bundle 30 | // https://github.com/rollup/rollup-plugin-node-resolve#usage 31 | // resolve(), 32 | 33 | // Resolve source maps to the original source 34 | sourceMaps(), 35 | ], 36 | }; 37 | -------------------------------------------------------------------------------- /src/lib.ts: -------------------------------------------------------------------------------- 1 | import 'reflect-metadata'; 2 | import { plainToClass } from 'class-transformer'; 3 | import { 4 | Validator as ClassValidator, 5 | ValidationError, 6 | ValidatorOptions 7 | } from 'class-validator'; 8 | 9 | export class ValidatorError extends Error { 10 | constructor(public validationErrors: ValidationError[]) { 11 | super('Validation Error'); 12 | 13 | Object.setPrototypeOf(this, ValidatorError.prototype); 14 | } 15 | } 16 | 17 | export function Validate(validatorOptions?: ValidatorOptions) { 18 | return (target: any, key: string, descriptor: PropertyDescriptor) => { 19 | const originalMethod = descriptor.value; 20 | const indices = Reflect.getMetadata( 21 | `validate_${key}_parameters`, 22 | target, 23 | key 24 | ); 25 | const types = Reflect.getMetadata('design:paramtypes', target, key); 26 | const targets = 27 | Reflect.getMetadata(`validate_${key}_targets`, target, key) || {}; 28 | 29 | descriptor.value = function(...args: any[]) { 30 | const errors = []; 31 | 32 | if (Array.isArray(indices)) { 33 | for (let i = 0; i < args.length; i++) { 34 | if (indices.indexOf(i) !== -1) { 35 | let value = args[i]; 36 | let validatorClass = types[i]; 37 | 38 | // if targets provided replace the value and validator classes 39 | if (targets && targets[i]) { 40 | value = getNestedObjectProperty(value, targets[i].targetKey); 41 | validatorClass = targets[i].validatorClass; 42 | // no value found under the specified key 43 | if (!value) { 44 | const error = new ValidationError(); 45 | error.constraints = { 46 | isDefined: `property ${targets[i].targetKey} is missing` 47 | }; 48 | 49 | throw new ValidatorError([error]); 50 | } 51 | 52 | if (Array.isArray(types[i].prototype)) { 53 | if (!Array.isArray(value)) { 54 | const error = new ValidationError(); 55 | error.constraints = { 56 | isArray: 'input param must be array' 57 | }; 58 | 59 | throw new ValidatorError([error]); 60 | } 61 | 62 | for (const argument of value) { 63 | const paramErrors = getValidationErrors( 64 | validatorClass, 65 | argument, 66 | validatorOptions 67 | ); 68 | if (paramErrors.length) errors.push(...paramErrors); 69 | } 70 | } 71 | } 72 | 73 | // if the validator class is array we want to validate each item in the array 74 | const paramErrors = getValidationErrors( 75 | validatorClass, 76 | value, 77 | validatorOptions 78 | ); 79 | if (paramErrors.length) errors.push(...paramErrors); 80 | } 81 | } 82 | 83 | if (errors.length) { 84 | throw new ValidatorError(errors); 85 | } 86 | 87 | return originalMethod.apply(this, args); 88 | } 89 | }; 90 | 91 | return descriptor; 92 | }; 93 | } 94 | 95 | /** 96 | * When provided the validatorClass validation will be performed on the provided key or root object 97 | * instead of argument itself. useful for when the validator data is located in a nested object. 98 | * 99 | * @param validatorClass - the validator class to use instead of the inferred ts type 100 | * @param targetKey - 101 | * @returns {(target: any, key: string, index) => void} 102 | */ 103 | export function Validator(validatorClass?: any, targetKey?: string) { 104 | return (target: any, key: string, index: number) => { 105 | const indices = 106 | Reflect.getMetadata(`validate_${key}_parameters`, target, key) || []; 107 | 108 | if (validatorClass !== undefined) { 109 | const targets = 110 | Reflect.getMetadata(`validate_${key}_targets`, target, key) || {}; 111 | targets[index] = { 112 | validatorClass, 113 | targetKey: targetKey || '' 114 | }; 115 | Reflect.defineMetadata(`validate_${key}_targets`, targets, target, key); 116 | } 117 | 118 | indices.push(index); 119 | 120 | Reflect.defineMetadata(`validate_${key}_parameters`, indices, target, key); 121 | }; 122 | } 123 | 124 | export function getValidationErrors( 125 | validatorClass: any, 126 | val: any, 127 | validatorOptions?: ValidatorOptions 128 | ): ValidationError[] { 129 | const data = plainToClass(validatorClass, val); 130 | const validator = new ClassValidator(); 131 | 132 | return validator.validateSync(data, validatorOptions); 133 | } 134 | 135 | export function getNestedObjectProperty(object: any, path: string) { 136 | let value = object; 137 | if (!path) return value; 138 | 139 | const list = path.split('.'); 140 | 141 | for (let i = 0; i < list.length; i++) { 142 | value = value[list[i]]; 143 | if (value === undefined) return undefined; 144 | } 145 | 146 | return value; 147 | } 148 | -------------------------------------------------------------------------------- /src/typescript-param-validator.ts: -------------------------------------------------------------------------------- 1 | export { Validate, Validator, ValidatorError } from './lib'; 2 | -------------------------------------------------------------------------------- /test/typescript-param-validator.test.ts: -------------------------------------------------------------------------------- 1 | import { IsEmail } from 'class-validator'; 2 | import { 3 | Validate, 4 | Validator, 5 | ValidatorError 6 | } from '../src/typescript-param-validator'; 7 | import { getNestedObjectProperty, getValidationErrors } from '../src/lib'; 8 | 9 | class BodyDto { 10 | @IsEmail() name: string; 11 | } 12 | 13 | describe('Validate param tests', () => { 14 | it('should selected nested property', () => { 15 | const data = { 16 | body: { 17 | item: { 18 | name: 'Danny' 19 | } 20 | } 21 | }; 22 | 23 | const response = getNestedObjectProperty(data, 'body.item.name'); 24 | expect(response).toEqual('Danny'); 25 | }); 26 | 27 | it('should return undefined property on non existent path', () => { 28 | const data = {}; 29 | 30 | const response = getNestedObjectProperty(data, 'body.item.name'); 31 | expect(response).toBeUndefined(); 32 | }); 33 | 34 | it('should return item on first level', () => { 35 | const data = { 36 | body: { 37 | name: 'Danny' 38 | } 39 | }; 40 | 41 | const response = getNestedObjectProperty(data, 'body'); 42 | expect(response.name).toEqual('Danny'); 43 | }); 44 | 45 | it('should return validation errors', () => { 46 | const response = getValidationErrors(BodyDto, { 47 | name: 'sds' 48 | }); 49 | 50 | expect(response.length).toEqual(1); 51 | const { target, property, constraints } = response[0]; 52 | expect(target).toEqual({ name: 'sds' }); 53 | expect(property).toEqual('name'); 54 | expect(constraints.isEmail).toEqual('name must be an email'); 55 | }); 56 | 57 | it('should not return validation errors', () => { 58 | const response = getValidationErrors(BodyDto, { 59 | name: 'sds@dasdas.com' 60 | }); 61 | 62 | expect(response.length).toEqual(0); 63 | }); 64 | 65 | it('should validate inferred ts type and throw', () => { 66 | class TestClass { 67 | @Validate() 68 | method(@Validator() body: BodyDto) { 69 | return 123; 70 | } 71 | } 72 | 73 | const instance = new TestClass(); 74 | 75 | try { 76 | instance.method({ 77 | name: 'asdas' 78 | }); 79 | } catch (e) { 80 | expect(e.message).toBe('Validation Error'); 81 | expect(e.validationErrors.length).toEqual(1); 82 | expect(e.validationErrors[0].constraints.isEmail).toEqual( 83 | 'name must be an email' 84 | ); 85 | } 86 | }); 87 | 88 | it('should validate specific validator type and key and fail', () => { 89 | class TestClass { 90 | @Validate() 91 | method( 92 | @Validator(BodyDto, 'body') 93 | body: any 94 | ) { 95 | return 123; 96 | } 97 | } 98 | 99 | const instance = new TestClass(); 100 | 101 | try { 102 | const response = instance.method({ 103 | name: 'asdas' 104 | }); 105 | } catch (e) { 106 | expect(e.message).toBe('Validation Error'); 107 | expect(e.validationErrors.length).toEqual(1); 108 | expect(e.validationErrors[0].constraints.isDefined).toEqual( 109 | 'property body is missing' 110 | ); 111 | } 112 | }); 113 | 114 | it('should validate specific validator type and key and succeed', () => { 115 | class TestClass { 116 | @Validate() 117 | method( 118 | @Validator(BodyDto, 'body') 119 | req: any 120 | ) { 121 | return 123; 122 | } 123 | } 124 | 125 | const instance = new TestClass(); 126 | 127 | const response = instance.method({ 128 | body: { 129 | name: 'asdas@gmail.com' 130 | } 131 | }); 132 | 133 | expect(response).toBe(123); 134 | }); 135 | 136 | it('should validate array types', () => { 137 | class TestClass { 138 | @Validate() 139 | method(@Validator(BodyDto) body: BodyDto[]) { 140 | return 123; 141 | } 142 | } 143 | 144 | const instance = new TestClass(); 145 | 146 | const response = instance.method([ 147 | { 148 | name: 'asdas@gmail.com' 149 | } 150 | ]); 151 | expect(response).toBe(123); 152 | 153 | try { 154 | instance.method([ 155 | { 156 | name: 'asdasm' 157 | } 158 | ]); 159 | } catch (e) { 160 | expect(e.message).toBe('Validation Error'); 161 | expect(e.validationErrors.length).toEqual(1); 162 | expect(e.validationErrors[0].constraints.isEmail).toEqual( 163 | 'name must be an email' 164 | ); 165 | } 166 | 167 | try { 168 | instance.method({ 169 | name: 'asdasm' 170 | } as any); 171 | } catch (e) { 172 | expect(e.message).toBe('Validation Error'); 173 | expect(e.validationErrors.length).toEqual(1); 174 | expect(e.validationErrors[0].constraints.isArray).toEqual( 175 | 'input param must be array' 176 | ); 177 | } 178 | }); 179 | }); 180 | -------------------------------------------------------------------------------- /tools/gh-pages-publish.ts: -------------------------------------------------------------------------------- 1 | const { cd, exec, echo, touch } = require("shelljs") 2 | const { readFileSync } = require("fs") 3 | const url = require("url") 4 | 5 | let repoUrl 6 | let pkg = JSON.parse(readFileSync("package.json") as any) 7 | if (typeof pkg.repository === "object") { 8 | if (!pkg.repository.hasOwnProperty("url")) { 9 | throw new Error("URL does not exist in repository section") 10 | } 11 | repoUrl = pkg.repository.url 12 | } else { 13 | repoUrl = pkg.repository 14 | } 15 | 16 | let parsedUrl = url.parse(repoUrl) 17 | let repository = (parsedUrl.host || "") + (parsedUrl.path || "") 18 | let ghToken = process.env.GH_TOKEN 19 | 20 | echo("Deploying docs!!!") 21 | cd("dist/docs") 22 | touch(".nojekyll") 23 | exec("git init") 24 | exec("git add .") 25 | exec('git config user.name "Dima Grossman"') 26 | exec('git config user.email "dima@grossman.io"') 27 | exec('git commit -m "docs(docs): update gh-pages"') 28 | exec( 29 | `git push --force --quiet "https://${ghToken}@${repository}" master:gh-pages` 30 | ) 31 | echo("Docs deployed!!") 32 | -------------------------------------------------------------------------------- /tools/semantic-release-prepare.ts: -------------------------------------------------------------------------------- 1 | const path = require("path") 2 | const { fork } = require("child_process") 3 | const colors = require("colors") 4 | 5 | const { readFileSync, writeFileSync } = require("fs") 6 | const pkg = JSON.parse( 7 | readFileSync(path.resolve(__dirname, "..", "package.json")) 8 | ) 9 | 10 | pkg.scripts.prepush = "npm run test:prod && npm run build" 11 | pkg.scripts.commitmsg = "validate-commit-msg" 12 | 13 | writeFileSync( 14 | path.resolve(__dirname, "..", "package.json"), 15 | JSON.stringify(pkg, null, 2) 16 | ) 17 | 18 | // Call husky to set up the hooks 19 | fork(path.resolve(__dirname, "..", "node_modules", "husky", "bin", "install")) 20 | 21 | console.log() 22 | console.log(colors.green("Done!!")) 23 | console.log() 24 | 25 | if (pkg.repository.url.trim()) { 26 | console.log(colors.cyan("Now run:")) 27 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 28 | console.log(colors.cyan(" semantic-release-cli setup")) 29 | console.log() 30 | console.log( 31 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 32 | ) 33 | console.log() 34 | console.log( 35 | colors.gray( 36 | 'Note: Make sure "repository.url" in your package.json is correct before' 37 | ) 38 | ) 39 | } else { 40 | console.log( 41 | colors.red( 42 | 'First you need to set the "repository.url" property in package.json' 43 | ) 44 | ) 45 | console.log(colors.cyan("Then run:")) 46 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 47 | console.log(colors.cyan(" semantic-release-cli setup")) 48 | console.log() 49 | console.log( 50 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 51 | ) 52 | } 53 | 54 | console.log() 55 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "target": "es5", 5 | "module":"es2015", 6 | "lib": ["es2015", "es2016", "es2017", "dom"], 7 | "strict": true, 8 | "sourceMap": true, 9 | "declaration": true, 10 | "allowSyntheticDefaultImports": true, 11 | "experimentalDecorators": true, 12 | "emitDecoratorMetadata": true, 13 | "declarationDir": "dist/types", 14 | "outDir": "dist/es", 15 | "typeRoots": [ 16 | "node_modules/@types" 17 | ] 18 | }, 19 | "include": [ 20 | "src" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint-config-standard", 4 | "tslint-config-prettier" 5 | ], 6 | "rules": { 7 | "semicolon": [true, "always"], 8 | "max-line-length": [true, 120] 9 | } 10 | } 11 | --------------------------------------------------------------------------------