javascript / expert
Snippet
Domain Model Validation via Proxies
Proxy objects allow for meta-programming by intercepting fundamental operations. In expert Node.js architectures, they are used to enforce runtime schema validation and data integrity on domain models without polluting the business logic.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const createSchemaProxy = (target, schema) => {return new Proxy(target, {set(obj, prop, value) {if (schema[prop] && typeof value !== schema[prop]) {throw new TypeError(`Property ${prop} must be of type ${schema[prop]}`);}obj[prop] = value;return true;}});};const user = createSchemaProxy({}, { age: 'number', name: 'string' });user.age = 30; // Works// user.age = '30'; // Throws TypeError
nodejs
Breakdown
1
set(obj, prop, value) { ... }
The 'set' trap intercepts every attempt to write a property to the target object.
2
throw new TypeError(...);
Enforces strict type constraints, preventing invalid data from entering the application state.