Giter Site home page Giter Site logo

plugin-change-flags's Introduction

Vuex ORM

Vuex ORM IsDirty / IsNew plugin

This project is supported by Generative Objects

Build Status License

This is a plugin for the Vuex-ORM library. It adds two flags $isDirty and $isNew (as boolean attributes) on any instance of the entities created through this library and updates their values automatically.

Installation

Simply run npm install @vuex-orm/plugin-change-flags --save in your favorite terminal.

Then, you need to install the plugin as any VuexORM plugin. In your store initialization code, simply add:

import VuexORMisDirtyPlugin from '@vuex-orm/plugin-change-flags';

and then

VuexORM.use(VuexORMisDirtyPlugin);

Usage

Once the plugin installed, every time you create a new instance of an entity, the $isDirty and $isNew will be automatically added.

The default value for those flags is false. They are automatically set to true in the following cases:

$isDirty

This flag is automatically set to true when:

  • creating a new instance using the createNew method;
  • updating the entity instance in the store, using the update action (insert and create mutation will not set this flag to true).

Preventing flag setting If you want to prevent the flag to be set to true when updating, you can pass preventDirtyFlag: true to the update and insertOrUpdate calls:

User.update({
    data: myUserToUpdate,
    preventDirtyFlag: true
});

$isNew

This flag is automatically set to true when calling the createNew method.

Hydrating with other default values

When calling the Model constructor new Model(), the default values for both flags is false.
Other values can be set by passing the initial record value to the constructor:

let user = new User({ id: 1, $isNew: true });

console.log(user.$isNew); // true (set through parameter)
console.log(user.$isDirty); // false (default value)

Methods

This plugin also adds the Model.createNew method and the allDirty & allNew getters.

createNew factory method

The plugin provides a new Model.createNew(insertInStore = true) method which returns a new instance of the entity, with both flags set to true by default and all other fields set to their default value.

This method copies VuexORM new method behavior. As such, it will automatically insert the newly created entity in the store.

If you don't want the created instance to be inserted in store directly, you can pass false as parameter.

โš ๏ธ When calling the createNew method without parameter, this will try to insert the given record directly in the store. It might fail if default value for the Primary Key is null. Try using an increment type attribute or a mutator to make sure your PK as a value.

allDirty getter

This new getter returns all entities marked as dirty currently in the store.

It can be used globally:

// Returns an array of mixed types with all entities
// currently marked as dirty in the store
let results = store.getters['entities/allDirty']();

or specifically to a type:

// Returns an array User entities currently marked as dirty in the store
let results = store.getters['entities/users/allDirty']();

allNew getter

This new getter returns all entities marked as new currently in the store.

It can be used globally:

// Returns an array of mixed types with all entities
// currently marked as new in the store
let results = store.getters['entities/allNew']();

or specifically to a type:

// Returns an array User entities currently marked as new in the store
let results = store.getters['entities/users/allNew']();

resetAllDirtyFlags action

This action will run through all the entities marked as dirty in your store and set the corresponding flag to false:

store.dispatch['entities/resetAllDirtyFlags']({}, { root: true });

Plugin Options

By default, the flags are named $isDirty and $isNew.
You can override those default by setting the corresponding options at plugin initialization.

Option name Description Default value
isNewFlagName Sets the name of the isNew flag $isNew
isDirtyFlagName Sets the name of the isDirty flag $isDirty
exposeFlagsExternally Adds the isNew and isDirty flags to the JSON stringified output true

In order to use those options, you can pass them as the second parameter of the install call:

VuexORM.use(VuexORMisDirtyPlugin, {
    isNewFlagName: 'IsNew',
    isDirtyFlagName: 'IsDirty',
    exposeFlagsExternally: true
});

License

License

This project is licensed under the MIT License - see the LICENSE.md file for details

plugin-change-flags's People

Contributors

adinvadim avatar kiaking avatar tvillaren avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

plugin-change-flags's Issues

Types?

Is there a type declaration file(s) for this library?

Reset flags on a single model instance when persisting

I want to reset both flags on a single model instance when persisting it to a back-end database. (Presently, I'm using the Vuex ORM GraphQL plugin for the latter purpose, but that is somewhat orthogonal.)

I've tried the following (I haven't tried working with updates to $isNew yet):

        myModelInstance.$update({ '$isDirty': false, preventDirtyFlag: true }).then(result => {
            console.log('update result: ', result)
            myModelInstance.$push()
        })

However, the output from the log statement indicates my update had no effect. What am I doing wrong here?

It seems to me there should be a more explicit means of resetting flags for just a single instance, rather than just for all instances as is presently the case.

store.$db is not a function

I've tried using let results = this.$store.getters['entities/allDirty']();, however I get store.$db is not a function error, what could be wrong?

"@vuex-orm/core": "0.36.1",
"@vuex-orm/plugin-change-flags": "^1.2.3",

createNew naming convention

Vuex-ORM differentiates Models create and insert.

I would say it is wise to respect that convention in the plugin-change-flags API as far as API coherence is concerned.

Not compatible with Vuex-ORM v0.35.0

After an update to the latest Vuex-ORM version this plugin is unfortunately broken.
For example, when I call 'entities/allDirty' or 'resetAllDirtyFlags', I get an error: store.$db is not a function

I think the problem is the breaking change in Vuex-ORM 0.35:

The Query now must receive database instance as the first argument.

For single instance cannot set isDirty: false using update (vuex-orm-core .36.3 and change-flags 1.2.3)

The code I am running is:

  console.log("trying to set isdirty false")
  ormRem.update({
    data: { 
      uuid: item.uuid,
      '$isDirty': false, 
    },
    preventDirtyFlag: true
  }).then(result => {
    console.log('update result: ', result)
  })
})

The output I get is:

image

The definition of model is at:
https://github.com/savantcare/ptfile/blob/master/ptclient/components/rem/vuex-orm/model.js

import { Model } from '@vuex-orm/core'
const { v1: uuidv1 } = require('uuid')

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

  static primaryKey = 'uuid' // Ref: https://vuex-orm.org/guide/model/defining-models.html#primary-key

  // 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 {
      uuid: this.uid(() => uuidv1()),
      uuidOfRemMadeFor: this.attr(null),
      remDescription: this.attr(null),
      notes: this.attr(null),
      priority: this.number(0),
      isAutoRem: this.number(0),
      recordChangedByUUID: this.attr(null),
      recordChangedFromIPAddress: this.attr(null),
      recordChangedFromSection: this.attr(null),
      // Why store time as a number? Since vuex-orm does not understand dates.
      // The data types that vuex-orm understands are given at: https://vuex-orm.org/guide/model/defining-models.html#generic-type
      ROW_START: this.number(0),
      ROW_END: this.number(0),
    }
  }
}

Is this a bug?

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.