Typescript Decorator Validate
JS
S
JavaScriptDemonstrates usage of TypeScript decorators for data validation, enhancing type safety and reducing runtime errors in TS projects.
1// decorators/validate.ts
2export function Validate(params: Array<any>): any {
3 return (target: Object, propertyKey: string): TypedPropertyDescriptor<any> => {
4 const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
5 const originalMethod = descriptor.value;
6
7 descriptor.value = function () {
8 const errors: Array<any> = [];
9 const body = arguments[0];
10
11 params.forEach((currentParam: any) => {
12 switch (currentParam.validate) {
13 case 'email':
14 const check = new RegExp('\\b[\\w\\.-]+@[\\w\\.-]+\\.\\w{2,4}\\b', 'gi');
15 if (!check.test(body[currentParam.param])) {
16 errors.push(currentParam);
17 }
18 break;
19 case 'required':
20 default:
21 if (!body[currentParam.param]) {
22 errors.push(currentParam);
23 }
24 break;
25 }
26 });
27
28 if (errors.length) {
29 return Promise.reject(errors);
30 } else {
31 return originalMethod.apply(this, arguments);
32 }
33 };
34
35 return descriptor;
36 };
37}
38
39
40// Usage
41import { Validate } from '../decorators/Validate';
42
43@Post()
44@Validate([
45 {
46 param: 'bannerSetId',
47 validate: 'required'
48 }
49])Created on 10/30/2018