Skip to content

nucleartide/validated-proxy

 
 

Repository files navigation

validated-proxy npm version Build Status Coverage Status

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.

Getting started

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'

Custom validators

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;

About

Validated ES2015 proxies. Still alpha, not for production use!

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 100.0%