npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

validated-proxy

v0.2.1

Published

Validated proxy

Downloads

17

Readme

validated-proxy npm version Build Status Coverage Status

A validated proxy represents a set of valid changes to be applied later onto any object. Each change is tested against an optional validation, and if valid, the change is stored and applied when executed.

Documentation

Latest documentation is available here.

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 updatedUser = validatedProxy(user, {
  validations: {
    name: [validatePresence(true), validateLength({ min: 4 })],
    age: [validatePresence(true), validateNumber({ gte: 18 })]
  }
});

// valid changes
updatedUser.name = 'Michael Bolton';
user.name; // 'Billy Bob'
updatedUser.flush();
user.name; // 'Michael Bolton'

// invalid changes
updatedUser.name = 'a';
user.name; // 'Billy Bob'
updatedUser.errors; // [
//   { key: 'name',
//     messages: ['name must be more than 4 characters'],
//     value: 'a'
//   }
// ]
updatedUser.flush();
user.name; // 'Billy Bob'

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 an example of creating a validator that validates if a value is of a given type:

import { ValidatorFunction } from 'validated-proxy';

type Primitive =
  | 'boolean'
  | 'number'
  | 'string'
  | 'symbol'
  | 'null'
  | 'undefined';
type NonPrimitive = 'object';
interface ValidatorOptions {
  type: Primitive | NonPrimitive;
}

const validateTypeof = ({ type }: ValidatorOptions): ValidatorFunction => {
  return (key, newValue, oldValue) => {
    return {
      message: `${newValue} is not of type '${type}'`,
      validation: typeof newValue === type
    };
  };
};

export default validateTypeof;

Now you can use your validator like so:

import { validatedProxy } from 'validated-proxy';
import validateTypeof from '../path/to/validateTypeof';

const user = { name: 'Billy Bob' };
const updatedUser = validatedProxy(user, {
  validations: { name: validateTypeof({ type: 'string' }) }
});

updatedUser.name = 123; // error

Custom validator type safety

If you're creating a custom validator that relies on the new value to be of a certain type, you can specify it as a generic type parameter to ValidatorFunction<T> (where T is the type of your new value):

import { ValidatorFunction } from 'validated-proxy';

interface ValidatorOptions {
  is: number;
}

const validateLength = ({
  is
}: ValidatorOptions): ValidatorFunction<string> => {
  return (key, newValue, oldValue) => {
    return {
      message: `${key} must be exactly ${is} characters`,
      validation: is === newValue.length // `newValue` is a `string`
    };
  };
};

export default validateLength;

More examples can be seen here.

Custom error handlers

The error handler is a function that is called when an invalid value is set. This is in addition to the error that is already stored in the cache. By default, the error handler is a no-op (does nothing). You can specify a custom error handler; for example, you could throw an error, log error messages, send them to a server, etc:

const proxy = validatedProxy(original, {
  errorHandler: errorMessages => { /** do something here **/},
  validations: /** ... */
});

Custom execution handlers

The execution handler is a function that is used to set the changes on the target object. By default, this is Object.assign. You can specify a custom execution handler; for example, you could use Lodash's assign, Ember's set, and so forth:

const proxy = validatedProxy(original, {
  executionHandler: (target, changes) => { /** do something here **/},
  validations: /** ... */
});