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