ApiResource.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. protected static _idLess: boolean = false
  9. protected static _assert: object | null = {}
  10. public static addIriEncodedField(name: string, target: ApiResource) {
  11. if (!this._iriEncodedFields) {
  12. this._iriEncodedFields = {}
  13. }
  14. this._iriEncodedFields[name] = target
  15. }
  16. public static getIriEncodedFields() {
  17. return this._iriEncodedFields
  18. }
  19. public static setIdField(name: string) {
  20. this._idField = name
  21. }
  22. public static getIdField() {
  23. return this._idField
  24. }
  25. public static setAsserts(assert: object) {
  26. this._assert = assert
  27. }
  28. public static getAsserts() {
  29. return this._assert
  30. }
  31. public static setIdLess() {
  32. this._idLess = true
  33. }
  34. public static isIdLess(): boolean {
  35. return this._idLess
  36. }
  37. /**
  38. * Fix the 'Cannot stringify arbitrary non-POJOs' warning, meaning server can not parse the store
  39. *
  40. * @see https://github.com/vuex-orm/vuex-orm/issues/255#issuecomment-876378684
  41. */
  42. toJSON() {
  43. return { ...this }
  44. }
  45. /**
  46. * Is it a newly created entity?
  47. *
  48. * If it is, it means this entity does not exist in the data source and that it has a temporary id
  49. */
  50. public isNew(): boolean {
  51. return (
  52. !this.id || (typeof this.id === 'string' && this.id.slice(0, 3) === 'tmp')
  53. )
  54. }
  55. }
  56. export default ApiResource