typed-schemas

1.0.2 • Public • Published

typed-schemas

JavaScript classes with type validation using JSON Schema

Using schema to instantiate defaults

const personSchema = {
  properties: {
    order: {
      type: 'number',
      default: 123
    }
  }
};

const person = new Schema(personSchema, {});

console.log(person.order); // outputs 123

Converting an object to a validated object

const schema = { properties: { prop: { type: 'number' } } };

const object = { prop: 'value' };

const typedObject = new Schema(schema, object);

// now typedObject.isInvalid == true

console.log(typedObject.isInvalid) // outputs validation errors

Building predefined types

const userSchema = { /* ... */ };

class User extends Schema {
  constructor(user = {}) {
    super(userSchema, user);
  }
}

const newUser = new User(); // newUser has `isInvalid` property

Extending AJV validator with options or plugins

const Ajv = require('ajv');
const AjvErrors = require('ajv-errors');

class PowerfulSchema extends Schema {
  constructor(schema, object) {
  
    // editing options
    const Ajv = new Ajv({ coerceTypes: true });
    
    // adding plugins
    const ajvPlugins = {
      'ajv-errors': AjvErrors,
    };
    
    super(schema, object, {
      ajv,
      ajvPlugins,
    });
  }
}

Package Sidebar

Install

npm i typed-schemas

Weekly Downloads

1

Version

1.0.2

License

MIT

Unpacked Size

3.01 MB

Total Files

298

Last publish

Collaborators

  • ggondim