Run ❯
Get your
own Node
server
❯
Run Code
Ctrl+Alt+R
Change Orientation
Ctrl+Alt+O
Change Theme
Ctrl+Alt+D
Go to Spaces
Ctrl+Alt+P
// Minimal local metadata helpers (no global mutations) const __metaStore: WeakMap
> = new WeakMap(); function __defineMetadata(key: string, value: any, target: object, propertyKey: string | symbol) { let targetMap = __metaStore.get(target); if (!targetMap) { targetMap = new Map(); __metaStore.set(target, targetMap); } const arr = targetMap.get(propertyKey) || []; const existingIndex = arr.findIndex((e: any) => e && e.__k === key); const item = { __k: key, __v: value }; if (existingIndex >= 0) { arr[existingIndex] = item; } else { arr.push(item); } targetMap.set(propertyKey, arr); } function __getOwnMetadata(key: string, target: object, propertyKey: string | symbol) { const targetMap = __metaStore.get(target); if (!targetMap) return undefined; const arr = targetMap.get(propertyKey) || []; const found = arr.find((e: any) => e && e.__k === key); return found ? found.__v : undefined; } function validateParam(type: 'string' | 'number' | 'boolean') { return function (target: any, propertyKey: string | symbol, parameterIndex: number) { const existingValidations: any[] = __getOwnMetadata('validations', target, propertyKey) || []; existingValidations.push({ index: parameterIndex, type }); __defineMetadata('validations', existingValidations, target, propertyKey); }; } function validate(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args: any[]) { const validations: Array<{index: number, type: string}> = __getOwnMetadata('validations', target, propertyKey) || []; for (const validation of validations) { const { index, type } = validation; const param = args[index]; let isValid = false; switch (type) { case 'string': isValid = typeof param === 'string' && param.length > 0; break; case 'number': isValid = typeof param === 'number' && !isNaN(param as any); break; case 'boolean': isValid = typeof param === 'boolean'; break; } if (!isValid) { throw new Error(`Parameter at index ${index} failed ${type} validation`); } } return originalMethod.apply(this, args); }; return descriptor; } class UserService { @validate createUser( @validateParam('string') name: string, @validateParam('number') age: number, @validateParam('boolean') isActive: boolean ) { console.log(`Creating user: ${name}, ${age}, ${isActive}`); } } const service = new UserService(); service.createUser('John', 30, true);
Expected console output:
Creating user: John, 30, true