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

proptypes-schema

v0.2.0

Published

Generic object schema modeled on React PropTypes

Downloads

763

Readme

PropTypes Schema

Generic object schema validation modeled on React PropTypes

Purpose

React's PropTypes offers a flexible way to define and validate component APIs.

This library extends the same API for generic object validation, which allows for a wider range of use. It includes a fork of React.PropTypes, intended for use in both development and production environments. It can be used with or without React, as well as server-side.

Example

import { PropTypes, validate } from 'proptypes-schema'

const personSchema = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
}

const data = {
  name: 'John'
}

const errors = validate(personSchema, data) // returns { age: Error }

Define schema

A schema is defined as a plain object with PropTypes as values.

Available types

All PropTypes validators from React are supported.

  • any, array, arrayOf, bool, boolOrString, element, func, instanceOf, node, number, numberOrString, object, objectOf, oneOf, oneOfType, shape, string, symbol

Please refer to their documentation (Typechecking With PropTypes) for details of use.

Nested schema objects

A plain object schema can be nested using PropTypes.shape.

const addressSchema = {
  city: PropTypes.string,
  country: PropTypes.string.isRequired,
}

const personSchema = {
  ...
  address: PropTypes.shape(addressSchema).isRequired
}

Validate

The validate method checks each property of a given object against the schema.

Schema.validate( schema, data )

import { validate } from 'proptypes-schema'

const errors = validate(personSchema, data)

It returns nothing if everything is valid; otherwise, it returns an object of keys and their errors.

{
  address: instanceof Error
}

Format

The format method creates a human-readable object from a given schema definition.

Schema.format( schema )

import { format } from 'proptypes-schema'

format(personSchema)

Example result:

{
  name: 'string.isRequired',
  age: 'number',
  role: 'oneOf(admin, user)'
}

Custom validators

Use addPropType to define custom validators.

addPropType( name, function )

import { addPropType } from 'proptypes-schema'

addPropType('notEmpty', (value, propName, schemaName) => {
  if (!value) {
    return `'${propName}' is empty for '${schemaName}'.`
  }
})

Note that the validator function receives the prop value as the first argument, instead of the whole props object as in React.PropTypes.

The validator is exposed as PropTypes[name], and decorated with an optional isRequired.

{
  key: PropTypes.notEmpty.isRequired
}

Errors

For a valid value, the validator must return nothing (null or undefined).

Anything else is considered an error, such as string, object, or an Error instance. This is passed to the errors object returning from validate(). It can be used, for example, to pass error codes.

Optionally, PropTypeError can be used in place of the native Error class, as a light-weight alternative that doesn't include a stack trace.

import { addPropType, PropTypeError } from 'proptypes-schema'

addPropType('notEmpty', (value, propName, schemaName) => {
  if (!value) {
    return new PropTypeError(`'${propName}' is empty for '${schemaName}'.`)
  }
})

Validator with argument

Use addPropTypeCreator for a validator that takes an argument.

import { addPropTypeCreator } from 'proptypes-schema'

addPropTypeCreator('shallowEqual', (value, propName, schemaName, arg) => {
  if (value !== arg) {
    return `The value of '${propName}' is not equal to '${arg}' for '${schemaName}'.`
  }
})

Example use:

{
  key: PropTypes.shallowEqual(something)
}

Schema instance

Another way to create a schema is by instantiating the Schema class, with a name (optional) and definition object. The name is used in validation errors.

import Schema from 'proptypes-schema'

const personSchema = new Schema('Person', { ... })

If you pass a function as the schema definition, it will be called with PropTypes as its argument. It can be used like so:

const personSchema = new Schema('Person', ({ string, number, oneOf }) => ({
  name: string.isRequired,
  age: number,
  role: oneOf(['admin', 'user']).isRequired
}))

Instance methods

validate - validate given object and return any errors

personSchema.validate(data)

format - return an object with schema definition as strings

personSchema.format()

Nested schema instances

Use the provided PropTypes.schema to create nested schema instances.

const addressSchema = new Schema('Address', { ... })

const personSchema = new Schema('Person', {
  address: PropTypes.schema(addressSchema).isRequired
})