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

model-persistence

v1.0.2

Published

Model persistence library.

Downloads

55

Readme

Model Persistence Library

Library intended for data persistence using HTTP or Storage API.

Demos:

Installing

Using npm:

npm install model-persistence

Using script:

<script src="./node_modules/objectmodel/dist/object-model.umd.js"></script>
<script src="./node_modules/axios/dist/axios.min.js"></script>
<script src="./bundle/model-persistence.min.js"></script>

Import Module

In Node.js:

const modelPersist = require('model-persistence');

In ES6 modules:

import modelPersist from 'model-persistence';

You have access to a global object modelPersist if you use the <script> tag.

Model Class

Model class is used to define models. It's from ObjectModel v2 library.

Object models validate nested object properties against a definition tree. You may consider them as definitions of classes with advanced validation options. They provide automatic validation at initial and future assignments of the properties of the instance objects.

Defining a model:

class Person extends modelPersist.Model({
    id: [Number],
    lastName: String,
    firstName: String 
}) {
   get fullName() {
       return `${this.firstName} ${this.lastName}`;
   }
}

New instance:

const rick = new Person({
    lastName: "Sanchez", 
    firstName: "Rick"
});

rick.lastName = 132;
// > TypeError: expecting lastName to be String, got Number 132
console.log(rick.fullName); // "Rick Sanchez"

Locator

Locator is responsible for where the data will be stored.

Using HTTPLocator to send data by HTTP:

class PersonLocator extends modelPersist.HTTPLocatorAbstract {
    /**
     * @inheritdoc
     */
    get basePath() {
        return '/person';
    }
}

Property basePath specify where is endpoint for persons. You can also override hostPath to specify host like https://google.com, default is empty.

You can use classes modelPersist.LocalStorageLocatorAbstract and modelPersist.SessionStorageLocatorAbstract, if you want to store data in localStorage or sessionStorage. It works analogically as HTTPLocatorAbstract, but property basePath specify prefix for storage keys.

Model Manager

Model Manager it's a data persistence and access layer. Each manager implements ModelManagerInterface and has methods: get, save and remove.

There are two types of managers:

HTTPModelManager

Used for data transfer by HTTP, requires HTTPLocator.

const manager = modelPersist.httpFactory.createManager(new PersonLocator());

StorageModelManager

Used for data transfer to Web Storage API, requires StorageLocator.

const manager = modelPersist.storageFactory.createManager(new PersonLocator());

Example of use:

const manager = modelPersist.httpFactory.createManager(new PersonLocator());

// Get model with id equals 1
const model = manager.get(1, Person);

// Change first name and save
model.firstName = 'Alexis';
manager.save(model).then((data) => {
    // data variable is object from server response
});

// Remove model
manager.remove(model).then((data) => {
    // data variable is object from server response
});

// Create new person
const gigi = new Person({firstName: 'Gigi', lastName: 'Amoroso'});
manager.save(model).then((data) => {
    // data variable is object from server response
});

HTTPModelManager methods

HTTPModelManager use the following methods:

Class method | HTTP method | Path | Description :---: | :---: | :---: | :---: get | GET | /person/1 | Get model by id. save | POST | /person | Save new model, when id is not defined. save | PUT | /person/1 | Save model. remove | DELETE | /person/1 | Remove model.

Repository

A repository is a class, that allows creation a data collection. Default repository implements only one method, i.e. findOne. Below shows, how to create a default repository.

Create a default HTTP repository:

const repository = modelPersist.httpFactory.createRepository(Person, new PersonLocator());

Create a default Web Storage repository:

const repository = modelPersist.storageFactory.createRepository(Person, new PersonLocator());

Example of use:

repository.findOne(id).then((person) => {
    console.log(person); // personal data
});

How create a custom repository

You must extend the default class:

class PersonHTTPRepository extends modelPersist.HTTPRepository
{
    findByFirstName(firstName) {
        return new Promise((resolve, reject) => {
            this._client.get(this._locator.getUrl(`/by-first-name/${firstName}`)).then((response) => {
                const ArrayModel = new modelPersist.Model.Array(this._modelClass);
                resolve(ArrayModel(this._manager.createInputTransformer().transform(response.data)));
            }).catch((e) => {
                reject(e);
            });
        });
    }
}

Now just change the type of repository in Locator:

class PersonLocator extends modelPersist.HTTPLocatorAbstract {
    /**
     * @inheritdoc
     */
    get basePath() {
        return '/person';
    }

    getRepositoryClass() {
        return PersonHTTPRepository;
    }
}

Example of use:

const repository = modelPersist.httpFactory.createRepository(Person, new PersonLocator());

repository.findByFirstName('Dolores').then((persons) => {
    console.log(persons); // all persons who have the name Dolores
});

Configuring HTTP Client

You can change the global client settings, by setter modelPersist.http.config.options.

modelPersist.http.config.options = {
    headers: {
        'X-API-Key': 'secret'
    }
};