Skip to content

Commit f6c6887

Browse files
author
Rodrigo Solis
committed
feat: Implement proxy validator and custom error
1 parent 0434dd6 commit f6c6887

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

src/error.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
2+
function ValidationError(errors) {
3+
this.name = 'ValidationError';
4+
this.message = JSON.stringify(errors, null, ' ');
5+
this.stack = new Error().stack;
6+
}
7+
ValidationError.prototype = Object.create(Error.prototype);
8+
ValidationError.prototype.constructor = ValidationError;
9+
10+
export default ValidationError;

src/index.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import ProxyValidator from './proxy';
2+
3+
export default ProxyValidator;

src/proxy.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/* eslint no-param-reassign: 0 */
2+
import ValidationError from './error';
3+
import { checkRules, applySanitizers } from './validation';
4+
5+
export default function ProxyValidator(schema, sanitizers) {
6+
const handler = {
7+
set(object, prop, value) {
8+
const { [prop]: rules } = schema;
9+
const { success, errors } = checkRules(rules, value);
10+
if (success) {
11+
const { [prop]: transforms } = sanitizers;
12+
object[prop] = applySanitizers(transforms, value);
13+
return success;
14+
}
15+
throw new ValidationError(errors);
16+
}
17+
};
18+
return function Proxied() {
19+
const target = {};
20+
return new Proxy(target, handler);
21+
};
22+
}

0 commit comments

Comments
 (0)