The idea behind a validated proxy is simple: it represents a set of valid changes to be applied onto any object. Each change is tested against an optional validation, and if valid, the change is stored and applied when executed.
Install using yarn
:
yarn add validated-proxy
Or using npm
:
npm install --save validated-proxy
Then import it and create a new validated proxy:
import { validatedProxy } from 'validated-proxy';
import { validatePresence, validateLength, validateNumber } from '../path/to/validators';
const user = {
name: 'Billy Bob',
age: 25
};
const bufferedProxy = validatedProxy(user, {
validations: {
name: [
validatePresence(true),
validateLength({ min: 4 })
],
age: [
validatePresence(true),
validateNumber({ gte: 18 })
]
}
});
bufferedProxy.name = 'Michael Bolton';
user.name; // 'Billy Bob'
bufferedProxy.flush();
user.name; // 'Michael Bolton'
A validator is a higher order function that returns a validation function. The validator can pass options to the validation function. The validation function is the function that is invoked when you set a value on the BufferedProxy
.
Here's a simple example of creating a validator that validates if a value is of a given type
:
import { IValidatorFunc, ValidationResult } from 'validated-proxy';
type Primitive =
| 'boolean'
| 'number'
| 'string'
| 'symbol'
| 'null'
| 'undefined';
type NonPrimitive = 'object';
interface IValidatorOptions {
type: Primitive | NonPrimitive;
}
const validateTypeof = ({ type }: IValidatorOptions): IValidatorFunc => {
return (key, newValue, oldValue) => {
return {
message: `${newValue} is not of type '${type}'`,
validation: typeof newValue === type
};
};
};
export default validateTypeof;