0.1.2 • Published 8 years ago

typecop v0.1.2

Weekly downloads
2
License
ISC
Repository
github
Last release
8 years ago

Build Status PRs Welcome js-standard-style

TypeCop - Type checking, auto hotfixing and error handling.

What is it, and why?

The motivation behind TypeCop was to find a way to check user entered values for an npm module I was building. While I wanted to know if a user had entered something invalid, I also wanted to try to correct their mistake, and let them know I've done so.

That's exactly what TypeCop does. Supply typecop with an assignment as well as the type you expect the assignment to be. TypeCop will then return a the assignment, unmodified, if correct. However if the assignemnt does not match the type you've provided, TypeCop will try to convert it safely to that type. Example, You expect the integer to 1 to be a string, TypeCop will then convert that number into a string, since it will cause no harm to the value.

TypeCop also protects you from forgetting to parse your stringified objects, arrays, etc.

Lastly if TypeCop cannot fix your assignment to match the requested type, it will send back a default value of the correct type to try to protect the application using the value from breaking but also throw an error letting you know everything has gone wrong.

Usage

First install TypeCop and require it.

npm install --save typecop
const TypeCop = require('typecop');

Basic Usage

Now you can get started! Simply provide the assignment, what type you expect it to be, any sub types (for Arrays), or Schemas for objects (more info below).

Dead simple example...

new TypeCop(['12323456'], 'integer').strict(); // returns 12323456

Shorthand usage...

const tc = new TypeCop();
tc.strict(['12323456'], 'integer'); // returns 12323456
tc.strict(67, 'integer'); // pass! returns 67

A bit more complex...

const validatedInteger = new TypeCop(['12323456'], 'integer', null, (warn, err) => {
  if (warn) {
    console.warn(warn); // TypeCop: converted ['12323456'] to an integer of 12323456.
  }
}).strict();

Using Object schemas

This doesn't quite work yet, it will be fully supported by the next release (hopefully no more than a day!)

const personSchema = {
  first: 'string',
  last: 'string',
  stomach: 'array',
  eyes: {
    color: 'string',
    open: 'boolean',
  },
};

const person = {
  first: 'matt',
  last: 'wski',
  stomach: ['eggs', 'bacon', 'bread'],
  eyes: {
    color: 'green',
    open: true,
  }
};

const validatedPerson = new TypeCop(person, 'object', personSchema, (warn, err) => {
  // TypeCop returns the object since it matches the schema, if any  key in the
  // object did not match the schema, it would follow the same procedure as
  // normal assignments to attempt corrections, or replace with default values.
}).strict();