robsontenorio/vue-api-query

Model defaults/Model override documentation suggestion

Closed this issue · 3 comments

I think it could help a lot of people if you added some details to the docs, regarding setting model defaults/override Model base class.

For example, I needed a way to define some default fields on my models, which then be overridden through the select() method in my components.

I solved it like seen below, hopefully, this can help others:

Base model (Model.js)

import { Model as BaseModel } from 'vue-api-query'

export default class Model extends BaseModel {
	constructor(...attributes) {
		attributes.length ? super(...attributes) : super()

		if (this._builder && this.defaultFields().length) {
			this._builder.select(...this.defaultFields())
		}
	}

	defaultFields() {
		return []
	}
}

Foobar.js

import Model from '@/models/Model'

export default class Foobar extends Model {
	defaultFields() {
		return ['id', 'firstName', 'lastName']
	}
}

-> ?fields[foobar]=id,firstName,lastName

Yet you can still use the select() method:
Foobar.select(['id', 'email'])
-> ?fields[foobar]=id,email

This seems related to or duplicate #223 . I should have just commented here. But I didn't see this first.
Anyway this is how I did it myself:

export default class Model extends BaseModel {
  constructor(...attributes) {
    super()

    if (attributes.length) {
      Object.assign(this, this.defaultAttributes(), ...attributes)
    }
  }

  defaultAttributes() {
    return {}
  }
}


export default class User extends Model {
  defaultAttributes() {
    return {
      selected: false // useful for checkbox or selection state
    }
  }
}

This seems related to or duplicate #223 . I should have just commented here. But I didn't see this first. Anyway this is how I did it myself:

export default class Model extends BaseModel {
  constructor(...attributes) {
    super()

    if (attributes.length) {
      Object.assign(this, this.defaultAttributes(), ...attributes)
    }
  }

  defaultAttributes() {
    return {}
  }
}


export default class User extends Model {
  defaultAttributes() {
    return {
      selected: false // useful for checkbox or selection state
    }
  }
}

I think your use case is different. You are looking into defining some default values for attributes on the model, where my example refers to which fields you are requesting from your API, using spaties query builder.

I see, thanks for the clarification 😇