{"id":26964423,"url":"https://github.com/nicklayb/modelizejs","last_synced_at":"2025-04-03T06:32:18.989Z","repository":{"id":57300425,"uuid":"79489925","full_name":"nicklayb/modelizejs","owner":"nicklayb","description":"Javascript model library Eloquent-like oriented using Axios for fetch request","archived":false,"fork":false,"pushed_at":"2017-07-13T13:46:13.000Z","size":35,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-15T16:49:04.284Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nicklayb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-01-19T20:01:11.000Z","updated_at":"2018-08-29T18:55:19.000Z","dependencies_parsed_at":"2022-09-09T06:10:36.992Z","dependency_job_id":null,"html_url":"https://github.com/nicklayb/modelizejs","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklayb%2Fmodelizejs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklayb%2Fmodelizejs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklayb%2Fmodelizejs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklayb%2Fmodelizejs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nicklayb","download_url":"https://codeload.github.com/nicklayb/modelizejs/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246948010,"owners_count":20859362,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-03T06:31:25.328Z","updated_at":"2025-04-03T06:32:18.967Z","avatar_url":"https://github.com/nicklayb.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# modelizejs\n###### By Nicolas Boisvert :: nicklay@me.com\n\n[![Build Status](https://travis-ci.org/nicklayb/modelizejs.svg?branch=master)](https://travis-ci.org/nicklayb/modelizejs)\n\n### Javascript model library Eloquent-like oriented using Axios for fetch request\n\n##### Purposes\n\nIt 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.\n\nFeel to make pull request and make suggestions\n\n## Usage\n\n### Extending\n\nYou can have look in *Demo* for more information. This example will use the JSONPlaceholder API for testing.\n\n```js\nvar Model = require('modelizejs');\n\nclass Users extends Model {\n    //  Required for the construction\n    constructor(attributes, withSetters) {\n        super(attributes, withSetters);\n        //  Will set the url to call (/users)\n        this.setUrl('users');\n    }\n\n    //  Will add a relation to Posts class using hasMany relation. It'll return all the instances related\n    postsRelated(callbacks) {\n        return this.hasMany(Posts, callbacks);\n    }\n\n    //  Accessor for the user fullname\n    getFullnameAttribute() {\n        return this.getAttribute('name') + ' (' + this.getAttribute('username') + ')';\n    }\n\n    //  Adds a base url for make the call. The class url will be appended\n    getBaseUrl() {\n        return 'https://jsonplaceholder.typicode.com';\n    }\n}\n\nclass Posts extends Model {\n    //  Required for the construction\n    constructor(attributes, withSetters) {\n        super(attributes, withSetters);\n        //  Will set the url to call (/users)\n        this.setUrl('posts');\n    }\n\n    //  Will add a relation to Users class using hasOne relation. It'll return the associated instance\n    userRelated(callbacks) {\n        return this.hasOne(Users, 'userId', callbacks);\n    }\n}\n\nUsers.find(1).then((user) =\u003e {\n    console.log(user);\n    /*\n        Will return an object looking like this :\n        Users {\n          attributes:\n           { id: 1,\n             name: 'Leanne Graham',\n             username: 'Bret',\n             email: 'Sincere@april.biz',\n             address:\n              { street: 'Kulas Light',\n                suite: 'Apt. 556',\n                city: 'Gwenborough',\n                zipcode: '92998-3874',\n                geo: [Object] },\n             phone: '1-770-736-8031 x56442',\n             website: 'hildegard.org',\n             company:\n              { name: 'Romaguera-Crona',\n                catchPhrase: 'Multi-layered client-server neural-net',\n                bs: 'harness real-time e-markets' } },\n          url: 'users',\n          primaryKey: 'id' }\n     */\n     console.log(user.get('fullname')); //  Leanne Graham (Bret)\n\n    user.get('posts').then((posts) =\u003e {\n        console.log(posts);\n        posts[0].get('user').then((user) =\u003e {\n            console.log(user); //   Returns the same user as above\n        });\n    });\n});\n        /*\n            Will return an array of Posts objects related to the selected user (1)\n            [ Posts {\n                attributes:\n                 { userId: 1,\n                   id: 1,\n                   title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',\n                   body: 'quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto' },\n                url: 'posts',\n                primaryKey: 'id' },\n              Posts {\n                attributes:\n                 { userId: 1,\n            ...\n            atttributes:\n             { userId: 1,\n               id: 10,\n               title: 'optio molestias id quia eum',\n               body: 'quo et expedita modi cum officia vel magni\\ndoloribus qui repudiandae\\nvero nisi sit\\nquos veniam quod sed accusamus veritatis error' },\n            url: 'posts',\n            primaryKey: 'id' } ]\n\n         */\n\n```\n\n### Fetch a model\n\nTo fetch a model, simply call one of those static methods :\n\n- `find(id)` / `get(id)`\n- `all()`\n\nExample\n```js\nUsers.get(1).then(user =\u003e {\n    // user is a User model instance\n});\nUsers.find(1).then(user =\u003e {\n    // user is a User model instance\n});\nUsers.all().then(users =\u003e {\n    // users is an array of User model instances\n});\n```\n\n### Saving models\n\n#### New instance\n\nWhen you create a new model with your attributes, you can call `save()` to do a POST request to the model url.\n\n```js\nlet user = new Users({\n    firstname: 'John',\n    lastname: 'Doe',\n    email: 'jdoe@email.com'\n});\nuser.save();\n```\n\nIf 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\n\n#### Update instance\n\nIf 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.\n\n```js\nUsers.get(1).then(user =\u003e {\n    user.set('firstname', 'Roberto');\n    user.save();\n});\n```\n\nIf you want to perform an insertion instead, call `setStored(false)` before your `save()`.\n\n## More\n\n### Casting related\n\nSometimes 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.\n\n```\ncastables() {\n    return {\n        posts: Posts\n    };\n}\n```\n\nWhen you will access the `posts` property with the get method, it will return you an array of `Posts` instead of an array of `Object`.\n\n### Creating relation\n\nAdd a method to your class called '{relation}Related', like 'commentsRelated' or 'userRelated'\n\nReturning an has many relation will make an API call to the related items. Let's take our example.\n```js\nclass Users extends Model {\n    //  constructor() ...\n\n    //  When calling the relation (.related('posts') or .get('posts')), it'll fetch to /users/{id}/posts\n    postsRelated(callbacks) {\n        return this.hasMany(Posts, callbacks);\n    }\n}\n```\n\nReturning 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.\n\n```js\nclass Posts extends Model {\n    //  constructor() ...\n\n    //  When calling the relation (.related('user') or .get('user')), it'll fetch to /users/{this.userId}\n    userRelated(callbacks) {\n        return this.hasOne(Users, 'userId', callbacks);\n    }\n}\n```\n\n## Conclusion\n\nThank you for using, testing and improving it and feel free to contact me for any question.\n\nEnding joke :\n\u003e !false, it's funny because it's true\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnicklayb%2Fmodelizejs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnicklayb%2Fmodelizejs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnicklayb%2Fmodelizejs/lists"}