Code Monkey home page Code Monkey logo

vuex-orm's Introduction

Vuex ORM

Travis CI JavaScript Style Guide

Vuex ORM is a plugin for Vuex to enable Object-Relational Mapping like access to the Vuex Store. Heavily inspired by Redux recipe of "Normalizing State Shape" and "Updating Normalized Data".

Vuex ORM lets you create "normalized" data schema within Vuex Store and provide fluent API to get, search and update Store state.

Documentation

You can check out the full documentation for Vuex ORM at https://revolver-app.gitbooks.io/vuex-orm.

Quick Start

Create Your Models

First, let's declare your models extending Vuex ORM Model. Here we assume that there are Post model and User model. Post model has a relationship with User โ€“ the post "belongs to" a user by author key.

// User Model
import Model from 'vuex-orm/lib/Model'

export default class User extends Model {
  // This is the name used as module name of the Vuex Store.
  static entity = 'users'

  // List of all fields (schema) of the post model. `this.attr` is used
  // for the generic field type. The argument is the default value.
  static fields () {
    return {
      id: this.attr(null),
      name: this.attr(''),
      email: this.attr(''),
    }
  }
}


// Post Model
import Model from 'vuex-orm/lib/Model'
import User from './User'

export default class Post extends Model {
  static entity = 'posts'

  static fields () {
    // `this.belongsTo` is for belongs to relationship.
    return {
      id: this.attr(null),
      user_id: this.attr(null),
      title: this.attr(''),
      body: this.attr(''),
      published: this.attr(false),
      author: this.belongsTo(User, 'user_id')
    }
  }
}

With above example, you can see that the author field at Post model has a relation of belongsTo with User model.

Create Your Modules

Next, you might want to create Vuex Module to register with models. However, the module could be an empty object.

// users module
export default {}

// posts module
export default {}

Register Models and Modules to the Vuex Store

Now it is time for you to register models and modules to the Vuex. To do so, you first have to register models to the Database and then register the database to Vuex Store as Vuex plugin.

import Vue from 'vue'
import Vuex from 'vuex'
import VuexORM from 'vuex-orm'
import Database from 'vuex-orm/lib/Database'
import User from './User'
import Post from './Post'
import users from 'users'
import posts from 'posts'

Vue.use(Vuex)

const database = new Database()

database.register(User, users)
database.register(Post, posts)

const store = new Vuex.Store({
  plugins: [VuexORM(database)]
})

export default store

Now you are ready to go. Vuex ORM is going to create entities module in Vuex Store. Which means you can access Vuex Store by store.state.entities.

Creating Records to the Vuex Store

You can use create mutation to create a new record in Vuex Store. Let's say we want to save a single post data to the store.

// Assuming this data structure is the response from the API backend.
const posts = [
  {
    id: 1,
    title: 'Hello, world!',
    body: 'Some awesome body...',
    author: {
      id: 1,
      name: 'John Doe',
      email: '[email protected]'
    }
  }
]

store.commit('entities/posts/create', { data: posts })

With above action, Vuex ORM creates the following schema at Vuex Store.

// Inside `store.state.entities`.
{
  posts: {
    data: {
      1: {
        id: 1,
        user_id: 1,
        title: 'Hello, world!',
        body: 'Some awesome body...',
        author: 1
      }
    }
  },

  users: {
    data: {
      1: {
        id: 1,
        name: 'John Doe',
        email: '[email protected]'
      }
    }
  }
}

See how posts and users are decoupled from each other. This is what it means for "normalizing" the data.

Accessing the Data

To access data, you may just access the store state directly as usual.

store.state.entities.posts.data[1].title       // <- 'Hello, world!'
store.state.entities.posts.data[1].author.name // <- 'John Doe'

However, Vuex ORM provides a way to query, and fetch data in an organized way through Vuex Getters.

// Fetch all post records. The result will be wrapped with Post model!
store.getters['entities/posts/all']()
// -> [
//   Post { id: 1, user_id: 1, title: 'Hello, world!', body: 'Some awesome body...', author: 1 },
//   ...
// ]

// Fetch single record with relation.
store.getters['entities/posts/query']().with('author').first()
// -> Post {
//   id: 1,
//   user_id: 1,
//   title: 'Hello, world!',
//   body: 'Some awesome body...',
//   author: User {
//     id: 1,
//     name: 'John Doe',
//     email: '[email protected]'
//   }
// }

Cool right? To get know more about Vuex ORM, please see the documentation

Currently Available Relationship

Since Vuex ORM is under development, currently supported relationships are below.

  • hasOne
  • belongsTo
  • hasMany
  • hasManyBy
  • hasAndBelongsToMany

Contribution

We are really excited that you are interested in contributing to Vuex ORM! Anything from raising an issue, submitting an idea of a new feature, or making a pull request is welcome!

Development

$ npm run dev

Compile files without removing the compiled file first. This is useful when you are using npm link during development with other bundlers such as Webpack. Plus the watch mode is enabled.

$ npm run build

Compile files into the lib directory.

$ npm run lint

Lint files using a rule of Standard JS.

$ npm run test

Run the test using Mocha Webpack.

$ npm run coverage

Generate test coverage.

License

The Vuex ORM is open-sourced software licensed under the MIT license.

vuex-orm's People

Contributors

ghosh avatar josx avatar kiaking avatar yuch avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.