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

opterator

v0.1.0

Published

Options validator with support for defaults.

Downloads

4

Readme

Opterator

Opterator is a simple, customizable validator/defaulter for options objects.

Getting started

Node.js

Install from npm:

npm install --save opterator

In your scripts, use

// CommonJS-style
var Opterator = require('opterator'),
      _Int = Opterator._Int,
      _String = Opterator._String,
      validate = Opterator.validate;
// ES6
import { _Int, _String, validate } from 'opterator';

Browser

Use one of the targets:

<script src="opterator.min.js"></script>

Opterator will be available as a global variable and on the window object.

How to use it

Let's assume you have a function

function makeUser(options) {
  // do something with options here
  console.log(options);
}

And you want your options to be validated. So create default some options with validation:

import { _Int, _String, validate } from 'opterator';

const defaultOptions = {
  id: _Int(0, 0),     // integer, default 0, min 0
  name: _String('')   // string, default empty
};

and change your makeUser to:

function makeUser(options) {
  options = validate(options, defaultOptions);
  // do something with options here
  console.log(options);
}

And when you call...

makeUser({ name: 'Larry' });

...options is now valid, and contains defaults from your validator where required.

{
  id: 0,
  name: "Larry"
}

In detail

Validators and Defaults

A Validator is a function, that either returns a clean value for a given option, or throws an error. You compose your defaultOptions of Validators:

const defaultOptions = {
  id: _Int(0, 0),     // a validator for integer, default 0, min 0
  name: _String('')   // a validator for string, default empty
};

_Int and _String are Validators, that come with Opterator. They take a default value, and sometimes additional arguments for validation, depending on the validator (e.g. min and max for numbers).

validate will call each Validator function with two arguments:

validatorFn(currentValue, valueName) {
  // Check currentValue here
  return currentValue;
}

When called by validate, Validators check and set the current value from the default, if required and possible, and then validate and return the value.

These Validators are available for the most common usecases:

  • _Number(defVal, minVal, maxVal)
    Validates any number, with optional default, min and max values.
  • _Int(defVal, minVal, maxVal)
    Same like _Number, but assures that value is an integer.
  • _String(defVal)
    A string with default.
  • _Object(defVal)
    An object with default.

See the API-documentation for more details.

Nested Validators

For _Object, defVal can be Validator, or a simple object. By this it's possible to nest options via validators, or via inline:

// Here createValidator is used, which returns a validate-function.
const validateRange = createValidator({
  start: _Int(0),
  length: _Int(0)
});

const validateUser = createValidator({
  id: _Int(0, 0),       // integer, default 0, min 0
  name: _String(''),    // string, default empty
  range: validateRange  // range, with default
});

// OR:

const validateUser = createValidator({
  id: _Int(0, 0),       // integer, default 0, min 0
  name: _String(''),    // string, default empty
  range: {
    start: _Int(0),
    length: _Int(0)
  }
});

Custom Validators

You can write your own Validator, say, for an email address, with a blacklist of forbidden domains:

// dont' use this one in production!
const emailRegex = /^([a-z]+)@(.*)$/i;

const _Email = (defVal = undefined, blacklist = undefined) => {
  return (currentValue, valueName) => {
    // default
    currentValue = ('undefined' === typeof currentValue)
      ? defVal
      : currentValue;
    // validate
    const result = emailRegex.exec(currentValue);
    if (!result) {
      throw new TypeError('Invalid email-address');
    }
    if (blacklist && (blacklist.indexOf(result[2]) !== -1)) {
      throw new Error('Email domain blacklisted');
    }
    // everything good
    return currentValue;
  }
};

const defaultOptions = {
  email: _Email('[email protected]', ['badguys.com'])
};

Plain Defaults without validation

If you don't need validation, but still want to use defaults, you can do so by using plain values:

const defaultOptions = {
  id: 0,     // default 0
  name: ''   // default empty
};

API

For a complete API description see the API-documentation.