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

@marianmeres/base-model

v0.1.1

Published

Base model class with schema, validation and change watch.

Downloads

0

Readme

@marianmeres/modelize

Single utility function modelize which proxies your model instance to monitor changes, validate, and more...

Install

npm i @marianmeres/modelize

Usage example

// SET UP ///////////////////////////////////////////////////////////////////////


// some model class
class User {
    // some public props ...
    firstname: string = '';
    lastname: string = '';
    // some methods ...
    whoami = () => [this.firstname, this.lastname].filter(Boolean).join(' ');
    // some getters ...
    get initials() {
        return [this.firstname.slice(0, 1), this.lastname.slice(0, 1)].join('').toUpperCase();
    }
}

// and model instance
const user = new User();
user.firstname = 'John';
user.lastname = 'Doe';
assert(user.whoami() === 'John Doe');
assert(user.initials === 'JD');


// BEGIN ACTUAL EXAMPLE /////////////////////////////////////////////////////////


// now create a new "modelized" version of the user instance
const modelized = modelize<User>(user);

// the "modelized" object is a new and different instance
assert(modelized !== user);

// but all props and methods are still available
assert(modelized.firstname === 'John');
assert(modelized.whoami() === 'John Doe');
assert(modelized.initials === 'JD');

// now, the new modelized version implements a bunch of new "virtual" utility methods
// (internally via proxy trap). They all start with "__" prefix to minimize the name
// collision risk with the original model class.
interface ModelizedMethods<T> {
    toJSON: () => Record<keyof T, any>;
    __hydrate: (data?: Partial<Record<keyof T, any>>, forceClean?: boolean) => any;
    __isDirty: () => (keyof T)[];
    __setClean: () => Modelized<T>;
    __setDirty: (keys: (keyof T)[]) => Modelized<T>;
    __getDirty: () => Partial<Record<keyof T, any>>;
    __validate: (assert?: boolean) => boolean;
    __setSchema: (schema: any) => Modelized<T>;
    __getSchema: () => any;
    __setValidator: (validator: Validator<T>) => Modelized<T>;
    __getValidator: () => Validator<T>;
    __setAllowAdditionalProps: (flag: boolean) => Modelized<T>;
    __onChange: (
        cb: (model: T, changed: { property: keyof T; old: any; new: any }) => any
    ) => Function;
    __pauseValidate: () => Modelized<T>;
    __resumeValidate: () => Modelized<T>;
}

// from now on, every instance update is monitored for changes
modelized.lastname = 'Lennon';
assert(modelized.__isDirty());
assert(_.isEqual({ lastname: 'Lennon' }, modelized.__getDirty()));

// and can be later marked as clean
modelized.__setClean();
assert(!modelized.__isDirty());

// you can also subscribe to changes
let log;
const unsubscribe = modelized.__onChange((model, changed) => (log = changed));
modelized.lastname = 'Wick';
assert(_.isEqual(log, { property: 'lastname', old: 'Lennon', new: 'Wick' }));
log = null; // reset

// and unsubscribe
unsubscribe();
modelized.lastname = 'McEnroe';
assert(log === null); // not subscribed anymore

// you can populate/hydrate multiple props at once, and by default, unknown props
// are silently ignored
modelized.__hydrate({ lastname: 'Depp', email: '[email protected]' })
assert(modelized.lastname === 'Depp');
assert(modelized.email === undefined);

// but you can allow setting additional props if needed
modelized.__setAllowAdditionalProps(true);
modelized.__hydrate({ lastname: 'Cash', email: '[email protected]' })
assert(modelized.lastname === 'Cash');
assert(modelized.email === '[email protected]');

// changes are synced with the original user instance as well
assert(user.email === '[email protected]');
assert(user.initials === 'JC');

// and, you can set json-schema to you model, to be auto validated all the time
modelized.__setSchema({
    type: 'object',
    properties: {
        firstname: { type: 'string' },
        lastname: { type: 'string' },
    },
});
assert(modelized.__validate());
assert.throws(() => (modelized.firstname = 123));

// if json-schema is not your thing, you can create your own validator function
// which has precedence over json-schema validation
modelized.__setValidator((model, schema, assert) => {
    const isJohn = !model.firstname || model.firstname === 'John';
    if (assert && !isJohn) throw new ModelizeValidationError('John only');
    return isJohn;
});
assert(modelized.__validate());

// only John is allowed
assert.throws(() => (modelized.firstname = 'Peter'));
assert(modelized.firstname === 'John');

It all works via shorthand notation and on POJO objects as well.

// modelize<T extends object>(
//     model: T,
//     data: Partial<Record<keyof T, any>> = {},
//     config: Partial<ModelizeConfig<T>> = {}
// ): Modelized<T>
const user = modelize(
    {}, // "pojo" instance
    { firstname: 'James', lastname: 'Bond' }, // initial data
    // `additionalProperties` must be set to `true` with pojos
    { additionalProperties: true, schema: null, validator: null } // config
);
assert(_.isEqual({ firstname: 'James', lastname: 'Bond' }, user.toJSON()));