vuex-orm / plugin-change-flags

Vuex ORM plugin for adding IsDirty / IsNew flags to model entities.
MIT License
24 stars 10 forks source link

store.$db is not a function #21

Open Marchiuzzz opened 3 years ago

Marchiuzzz commented 3 years ago

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",

zorn-v commented 3 years ago

Those getters like a crap. If you need something like Model.allDirty() - do not use them, and forgot about it existence. Better to make base class wth allDirty static method and extends from it. Something like

//BaseModel
import { Model } from '@vuex-orm/core'

export default class Base extends Model {
  static fetchAll() {
    return this.api().get(this.entity)
  }

  static getModified() {
    function clearServiceFields(ent) {
      Object.keys(ent).forEach(key => {
        if (key[0] === '$') {
          delete ent[key]
        }
      })
      return ent
    }
    const created = this.query().where('$isNew', true).get().map(clearServiceFields)
    const updated = this.query().where(rec => {
      return rec.$isDirty && !rec.$isNew && !rec.$trashed()
    }).get().map(clearServiceFields)
    const deleted = this.query().onlyTrashed().get().map(clearServiceFields)

    if (created.length || updated.length || deleted.length) {
      return {created, updated, deleted}
    }

    return null
  }

  static saveAll() {
    const modified = this.getModified()
    if (modified) {
      return this.api().post(this.entity, modified, {save: false})
    }
    return Promise.resolve()
  }
}

Actual model

import BaseModel from './BaseModel'
import { v4 as uuid4 } from 'uuid'

export default class Project extends BaseModel {
  static entity = 'projects'
  static primaryKey = '_id'

  static fields () {
    return {
      _id: this.uid(() => uuid4()),
      title: this.string(''),
    }
  }
}