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

shapetype

v6.0.0

Published

Define shapes and types and use them for data/structure validation

Downloads

43

Readme

ShapeType

Define shapes and types and use them for data/structure validation.


API

Type

Types allow you to define what type of data you expect a value to be.

Type Definitions:

  • Type.bool() for a boolean value
  • Type.number() for a number
  • Type.string() for a string
  • Type.value(val1[, val2, val3]) for an exact match of one or more values.
  • Type.datetime() for a Date object
  • Type.null() for a null value
  • Type.undefined() for an undefined value
  • Type.object() for an object literal
    • Note: You'll often want to use a Shape instead of Type.object() (see below).
  • Type.array() for an array.
    • Note: You'll often want to use arrayOf() instead of Type.array()(see below).
  • Type.custom(isType[, name]) allows you to define a custom Type.
    • isType should be a method that accepts a value and returns a boolean.
    • name is an optional value that will be stored as Type.value internally.
    • Example: const EmailType = Type.custom(val => isEmail(val), 'EMAIL');

Type Methods

  • .compare(val): returns true/false whether val matches the Type.
    • Example:
  • .validate(val): returns an validation object assessing whether val matches the Type.
    • Example:
      • EmailType.validate('[email protected]') ~ { invalidTypeFields: [] }
      • EmailType.validate('test=test') ~ { invalidTypeFields: [ 'test=test' ] }
  • .or(): allows you to chain a list of Types together
    • Example: const assignedTo = Type.number().or(Type.null())

arrayOf(Type|Shape)

Indicates that there is an array of the provided value.

When validate is called on a value defined by arrayOf(), an empty array will be returned if all values pass their tests. An array of validation objects with an additional index key will be returned if any of the array's values do not pass their test.


optional()

Wraps a Type, Shape, or ArrayContainer to indicate that a given field isn't required in a shape definition. Tests will still pass if the value is omitted.

const Event = defineShape({
  id: Type.number(),
  name: Type.string(),
  createdBy: optional(User),
  scheduledAt: optional(Type.datetime()),
  guests: arrayOf(User),

defineShape({})

Returns a Shape when provided with an object of key/Type pairs.

const User = defineShape({
  id: Type.number(),
  name: Type.string(),
  assignedTo: Type.number().or(Type.null()),
})

You can also nest Shapes within other Shapes.

const Event = defineShape({
  id: Type.number(),
  name: Type.string(),
  createdBy: User,
  guests: arrayOf(User),
})

Shape Methods

  • .compare(obj) returns true/false whether obj matches the pattern defined by the Shape.
    • Example:
      • User.compare({ id: 2, name: 'Test', assignedTo: 12 }) ~ true
      • User.compare({ id: 2, name: 'Test', assignedTo: 'Joe' }) ~ false
  • .partialCompare(obj) same as .compare(obj), but only tests for the keys present in obj.
    • Example:
      • User.partialCompare({ id: 2 }) ~ true
      • User.partialCompare({ id: 'Toby' }) ~ false
  • .validate(obj) returns a validation object reflecting the test results of the individual values defined by the shape.
    • The validation object consists of three arrays:
      • missingFields: fields that are defined in the Shape but missing from the object
      • extraFields: fields that are not defined in the Shape but are included in the object
      • invalidTypeFields: fields that don't match the Type defined by the Shape
    • Example:
      • User.validate({ id: 2, name: 'Test', assignedTo: 12 }) ~ { missingFields: [], extraFields: [], invalidTypeFields: [] }
      • User.validate({ id: 2, name: 'Test', assignedTo: 'Joe' }) ~ { missingFields: [], extraFields: [], invalidTypeFields: [ 'assignedTo' ] }
      • User.validate({ name: 'Test', assignedTo: 12 }) ~ { missingFields: [ 'id ], extraFields: [], invalidTypeFields: [] }
      • User.validate({ id: 2, name: 'Test', assignedTo: 12, isDog: true }) ~ { missingFields: [], extraFields: [ 'isDog' ], invalidTypeFields: [] }
  • .partialValidate(obj) same as .validate(obj), but only tests for the keys present in obj.
    • Example:
      • User.partialValidate({ id: 2 }) ~ { missingFields: [], extraFields: [], invalidTypeFields: [] }
      • User.partialCompare({ id: 'Toby' }) ~ { missingFields: [], extraFields: [], invalidTypeFields: [ 'id' ] }

extendShape(existingShape, obj)

Allows you to build off of an existing shape. A new Shape instance will be returned.

const Rectangle = defineShape({
  length: Type.number(),
  width: Type.number(),
});

const Box = extendShape(Rectangle, { height: Type.number() });

Additional Examples

Usage in testing

You can use Shapes with a testing library such as Jest for type assertions.

it ('should return the user', () => {
  expect(UserShape.compare(user)).toEqual(true);	
});

Usage in field validation

const missingFields = UserShape.validate(user));
if (missingFields.length > 0){
  onError(missingFields);
} else {
  onSave(user);
}