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

modelizejs

v1.3.7

Published

Javascript model library Eloquent-like oriented using Axios for fetch request

Downloads

33

Readme

modelizejs

By Nicolas Boisvert :: [email protected]

Build Status

Javascript model library Eloquent-like oriented using Axios for fetch request

Purposes

It helps you fetch object from an API using Laravel Eloquent-like model extensions. This can be helpful to customize accessors or to fetch relations directly from a primary instance. It uses the awesome Axios library to make the ajax request. It all use ES6 and I highly recommend using it when extending.

Feel to make pull request and make suggestions

Usage

Extending

You can have look in Demo for more information. This example will use the JSONPlaceholder API for testing.

var Model = require('modelizejs');

class Users extends Model {
    //  Required for the construction
    constructor(attributes, withSetters) {
        super(attributes, withSetters);
        //  Will set the url to call (/users)
        this.setUrl('users');
    }

    //  Will add a relation to Posts class using hasMany relation. It'll return all the instances related
    postsRelated(callbacks) {
        return this.hasMany(Posts, callbacks);
    }

    //  Accessor for the user fullname
    getFullnameAttribute() {
        return this.getAttribute('name') + ' (' + this.getAttribute('username') + ')';
    }

    //  Adds a base url for make the call. The class url will be appended
    getBaseUrl() {
        return 'https://jsonplaceholder.typicode.com';
    }
}

class Posts extends Model {
    //  Required for the construction
    constructor(attributes, withSetters) {
        super(attributes, withSetters);
        //  Will set the url to call (/users)
        this.setUrl('posts');
    }

    //  Will add a relation to Users class using hasOne relation. It'll return the associated instance
    userRelated(callbacks) {
        return this.hasOne(Users, 'userId', callbacks);
    }
}

Users.find(1).then((user) => {
    console.log(user);
    /*
        Will return an object looking like this :
        Users {
          attributes:
           { id: 1,
             name: 'Leanne Graham',
             username: 'Bret',
             email: '[email protected]',
             address:
              { street: 'Kulas Light',
                suite: 'Apt. 556',
                city: 'Gwenborough',
                zipcode: '92998-3874',
                geo: [Object] },
             phone: '1-770-736-8031 x56442',
             website: 'hildegard.org',
             company:
              { name: 'Romaguera-Crona',
                catchPhrase: 'Multi-layered client-server neural-net',
                bs: 'harness real-time e-markets' } },
          url: 'users',
          primaryKey: 'id' }
     */
     console.log(user.get('fullname')); //  Leanne Graham (Bret)

    user.get('posts').then((posts) => {
        console.log(posts);
        posts[0].get('user').then((user) => {
            console.log(user); //   Returns the same user as above
        });
    });
});
        /*
            Will return an array of Posts objects related to the selected user (1)
            [ Posts {
                attributes:
                 { userId: 1,
                   id: 1,
                   title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
                   body: 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto' },
                url: 'posts',
                primaryKey: 'id' },
              Posts {
                attributes:
                 { userId: 1,
            ...
            atttributes:
             { userId: 1,
               id: 10,
               title: 'optio molestias id quia eum',
               body: 'quo et expedita modi cum officia vel magni\ndoloribus qui repudiandae\nvero nisi sit\nquos veniam quod sed accusamus veritatis error' },
            url: 'posts',
            primaryKey: 'id' } ]

         */

Fetch a model

To fetch a model, simply call one of those static methods :

  • find(id) / get(id)
  • all()

Example

Users.get(1).then(user => {
    // user is a User model instance
});
Users.find(1).then(user => {
    // user is a User model instance
});
Users.all().then(users => {
    // users is an array of User model instances
});

Saving models

New instance

When you create a new model with your attributes, you can call save() to do a POST request to the model url.

let user = new Users({
    firstname: 'John',
    lastname: 'Doe',
    email: '[email protected]'
});
user.save();

If you have an existing attributes object and you want to persist it in the database, simply do the above and call setStored() before the save(). It'll do a PUT request to /users/{id} instead

Update instance

If you obtained an instance by a get or a find. Calling the .save() method will perform a PUT request to /users/{id} to update it.

Users.get(1).then(user => {
    user.set('firstname', 'Roberto');
    user.save();
});

If you want to perform an insertion instead, call setStored(false) before your save().

More

Casting related

Sometimes you wish an attribute to be called as a specific class. If, for instance, our User model would come with an array of related posts, you could override the static method castables() to return an object within a attribute:class format.

castables() {
    return {
        posts: Posts
    };
}

When you will access the posts property with the get method, it will return you an array of Posts instead of an array of Object.

Creating relation

Add a method to your class called '{relation}Related', like 'commentsRelated' or 'userRelated'

Returning an has many relation will make an API call to the related items. Let's take our example.

class Users extends Model {
    //  constructor() ...

    //  When calling the relation (.related('posts') or .get('posts')), it'll fetch to /users/{id}/posts
    postsRelated(callbacks) {
        return this.hasMany(Posts, callbacks);
    }
}

Returning an has one relation will make an API call to the related item specified by the foreign key as second parameter. Let's take our example.

class Posts extends Model {
    //  constructor() ...

    //  When calling the relation (.related('user') or .get('user')), it'll fetch to /users/{this.userId}
    userRelated(callbacks) {
        return this.hasOne(Users, 'userId', callbacks);
    }
}

Conclusion

Thank you for using, testing and improving it and feel free to contact me for any question.

Ending joke :

!false, it's funny because it's true