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

model-json

v0.2.3

Published

Enforces a schema on a JSON object.

Downloads

15

Readme

model-json

model-json is a library which enforces a schema on a JSON object.

When the schema is applied to an object, coercion is applied where applicable and keys which do not belong are stripped. Keys which are within the schema are validated and are either removed, set to defaults, or rejected per configuration.

See usage examples to get started with the library.

Install

$ npm i model-json -S

Usage

Example of type coercion and field stripping:

import model from 'model_json'
const example = new model({
  fieldA: {
    type: 'string'
  },
  fieldB: {
    type: 'number'
  }
})

console.log(example.validate({
  fieldA: 5,
  fieldB: '15',
  fieldC: 'this should be gone'
})) // -> { fieldA: '5', fieldB: 15 }
console.log(example.validate({
  fieldA: 5,
  fieldB: 'Since this field is not required and is not a number, it will be removed from the object.'
})) // -> { fieldA: '5' }

Example of defaults:

import model from 'model_json'
const example = new model({
  fieldA: {
    type: 'string',
    required: true,
    default: 'No string provided'
  },
  fieldB: {
    type: 'string',
    default: `This default will not appear by default because the field is not required. This behavior is configurable via an option, as shown.`
  }
})

console.log(example.validate({ })) // -> { fieldA: 'No string provided' }
console.log(example.validate({ }, { defaults: true })) // -> { fieldA: 'No string provided', fieldB: 'This default <clip> ...' }
import model from 'model_json'
const example = new model({
  fieldA: {
    type: 'number',
    required: true,
    default: 1337
  }
})

console.log(example.validate({ })) // -> { fieldA: 1337 }
console.log(example.validate({ fieldA: 3 })) // -> { fieldA: 3 }
console.log(example.validate({ fieldA: '3' })) // -> { fieldA: 3 }
console.log(example.validate({ fieldA: 'apple' })) // -> { fieldA: 1337 }

Example of validation:

import model from 'model_json'
const exampleA = new model({
  field: {
    type: 'string',
    valid: str => str.length > 0
  }
})

console.log(exampleA.validate({ field: '' })) // Error: Key field did not pass custom valid test, ''.
console.log(exampleA.validate({ field: 'Test' })) // -> { field: 'Test' }

// Valid is applied *after* default is set
// Usage of default on rejection may be forced with a flag as shown
const exampleB = new model({
  field: {
    type: 'string',
    required: true,
    default: '',
    valid: str => str.length > 0
  }
})

console.log(exampleB.validate({ })) // Error: Key field did not pass custom valid test, ''.
console.log(exampleB.validate({ }, { defaultOnReject: true })) // -> { field: '' }

Documentation

Types

Type | Coercion | Explanation --- | --- | --- any | No | No value is disregarded array | No | Values which do not return true from Array.isArray are disregarded boolean | Yes | null is disregarded; true, 'true', 't', 'yes', 'y', 1, and '1' are considered true -- all other values false function | No | Type of field must be function, otherwise disregarded integer | Yes | Disregards values which are NaN when parsed; does not allow alphabetic characters while parsing; removes any precision (15.2 -> 15) number | Yes | Disregards values which are NaN when parsed; does not allow alphabetic characters while parsing object | No | Type of field must be object, otherwise disregarded string | Yes | Disregards null; all other values are coerced to a string via .toString()

Methods

  • (constructor)(< object >schema)
    • schema - object - The schema for this model.
      • key1 - object - Specifies the type, validation, default, etc for a key within the schema.
        • type - string - The type of this value, see Types above.
        • preparse - function - Synchronously allows modification of the value before type coercion
        • postparse - function - Synchronously allows modification of the value after type coercion
        • required - boolean - Specify whether or not this value is required to be provided to the schema
        • default - (as specified) - Specifies a default value when the value is required but missing from the schema
        • valid - function - Synchronously or Asynchronously validates a value after coercion (use validate and validateAsync respectively)
      • ... key2 ...
      • ... key3 ...
      • ...
  • validate(< object >object [, < object >config]) - (object) - Synchronously applies the schema to the provided object adhering to the provided options.
    • object - object - The object which the schema is being applied to.
    • config - object - The options which alter schema application.
      • defaults - boolean - Sets keys which are not required but missing from the schema to their provided default.
      • defaultOnReject - boolean - Sets a key to its provided default value when it fails its valid check.
  • validateAsync(< object >object [, < object >config]) - (Promise) - Asynchronously applies the schema to the provided object adhering to the provided options (required when schema contains valid clauses which return a Promise).
    • object - object - see validate
    • config - object - see validate