modelike
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

modelike - JavaScript object models

Node version NPM Downloads Minified size License: MIT

A lightweight library that allows for object schema validation.

Object validation

For object validation one defines rules for each property of the object. Combined, rules define the validation schema. Each rule must contain a type. Other settings are optional.

type Rule = {
  type: 'string' | 'boolean' | 'number'; // type error
  required?: boolean; // required error
  regexp?: RegExp; // format error, only when type = 'string'
  custom?: (value, obj) => boolean; // custom error; if custom === false, it gives an error
};

type Schema = {
  [key: string]: Rule; // also for nested properties, e.g. "nested.property"
};

when

An object can be validated by using the validate function of modelike. It returns an object indicating which properties of the object have errors. It also indicates the type of error, unless you set a custom error message.

import { validator } from 'modelike';

const errors = validator(obj, schema);
// { "nested.property": "type" | "required" | "format" | "other" | "my custom message" }

Object picking

Use the models to change the shape of the object (basically removing properties).

import { pick } from 'modelike';

const _obj = pick(obj, schema);
// new object with limited properties, based on schema

Package Sidebar

Install

npm i modelike

Weekly Downloads

0

Version

0.1.0

License

MIT

Unpacked Size

10.7 kB

Total Files

11

Last publish

Collaborators

  • kevtiq