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

@chialab/schema-model

v1.3.4

Published

Generate Model classes based on JSON Schema definition.

Downloads

213

Readme


Install

npm install @chialab/schema-model --save

Usage

The SchemaModel object can be extended or use as factory to create Model classes dynamically.

Extend the base model

import SchemaModel from '@chialab/schema-model';

class PersonModel extends SchemaModel {
    static get schema() {
        return {
            type: 'object',
            properties: {
                id: {
                    type: 'number',
                },
                firstName: {
                    type: 'string',
                },
                lastName: {
                    type: 'string',
                },
                married: {
                    type: 'boolean',
                },
            },
            required: ['id'],
        };
    }
}

let person = new PersonModel({
    id: 1,
});

As factory

const PersonModel = SchemaModel.create({
    type: 'object',
    properties: {
        id: {
            type: 'number',
        },
        firstName: {
            type: 'string',
        },
        lastName: {
            type: 'string',
        },
        married: {
            type: 'boolean',
        },
    },
    required: ['id'],
});

let person = new PersonModel({
    id: 1,
});

Validation

SchemaModel uses tv4 to validate model data on creation and update.

Get the validation state

Use the .validate method to retrieve the validation state of the model.

let person = new PersonModel();
let validation = person.validate();
console.log(validation.valid); // --> false
console.log(validation.error.message); // --> 'Missing required property: id'

Creation and update

When a set of data is pass to the constructor or to the .set method, the model will try to validate them. If the validation fails, an exception is thrown and the new data will not be set.

try {
    let person = new PersonModel({ firstName: 'Alan' });
} catch (err) {
    console.log(err.message); // --> 'Missing required property: id'
}
try {
    let person = new PersonModel({ id: 1, firstName: 'Alan' });
    person.set({
        lastName: 10,
    });
} catch (err) {
    console.log(err.message); // --> 'Invalid type: number (expected string)'
}

Skip validation

By the way, you can disabled the auto validation passing validate: false as option for constructor/set.

let person = new PersonModel({ firstName: 'Alan' }, { validate: false });
let validation = person.validate();
console.log(validation.valid); // --> false
console.log(validation.error.message); // --> 'Missing required property: id'

Getting and setting data

In order to get an object representing model data, you can use the .toJSON helper, which converts all model instances in javascript plain objects:

let person = new PersonModel({ id: 1, firstName: 'Alan' });
console.log(person); // --> PersonModel{ id: 1, firstName: 'Alan' }
console.log(person.toJSON()); // --> { id: 1, firstName: 'Alan' }

You can access a property of the model using the .get method, or accessing directly to its reference:

let person = new PersonModel({ id: 1, firstName: 'Alan' });
console.log(person.get('id')); // --> 1
console.log(person.firstName); // --> 'Alan'

By the way, you should always use the .set method to update the model:

let person = new PersonModel({ id: 1, firstName: 'Alan' });

// ok!
person.set({
    lastName: 'Turing',
});

// no no no
person.lastName = 'Turing';

Define getters and setters

Using ES2015 classes (or Object.defineProperty programmatically), you can define a custom getter and setter for a property:

import SchemaModel from '@chialab/schema-model';

class PersonModel extends SchemaModel {
    static get schema() {
        return {
            type: 'object',
            properties: {
                id: {
                    type: 'number',
                },
                firstName: {
                    type: 'string',
                },
                lastName: {
                    type: 'string',
                },
                married: {
                    type: 'boolean',
                },
            },
            required: ['id'],
        };
    }

    set married(married) {
        // passing the `internal: true` options you can set a private property.
        this.set('married', !!married, { internal: true });
    }

    get married() {
        // setup a default value for a property
        return this.get('married', { internal: true }) || false;
    }
}

let person = new PersonModel({
    id: 1,
});
console.log(person.married); // --> false
person.set({ married: true });
console.log(person.married); // --> true