ApiResource.ts 1.5 KB

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