ApiResource.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { Model } from 'pinia-orm'
  2. /**
  3. * Base class for resources that can be fetched from the API
  4. */
  5. class ApiResource extends Model {
  6. protected static _iriEncodedFields: Record<string, ApiResource>
  7. protected static _idField: string
  8. public static addIriEncodedField(name: string, target: ApiResource) {
  9. if (!this._iriEncodedFields) {
  10. this._iriEncodedFields = {}
  11. }
  12. this._iriEncodedFields[name] = target
  13. }
  14. public static getIriEncodedFields() {
  15. return this._iriEncodedFields
  16. }
  17. public static setIdField(name: string) {
  18. this._idField = name
  19. }
  20. public static getIdField() {
  21. return this._idField
  22. }
  23. /**
  24. * Fix the 'Cannot stringify arbitrary non-POJOs' warning, meaning server can not parse the store
  25. *
  26. * @see https://github.com/vuex-orm/vuex-orm/issues/255#issuecomment-876378684
  27. */
  28. toJSON() {
  29. return { ...this }
  30. }
  31. /**
  32. * Is it a newly created entity?
  33. *
  34. * If it is, it means this entity does not exist in the data source and that it has a temporary id
  35. */
  36. public isNew(): boolean {
  37. return (
  38. !this.id || (typeof this.id === 'string' && this.id.slice(0, 3) === 'tmp')
  39. )
  40. }
  41. }
  42. export default ApiResource