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. export class ApiResource extends Model {
  6. private _model: typeof ApiResource | undefined = undefined;
  7. static readonly relations: Record<string, ApiResource>
  8. public getModel() {
  9. return this._model
  10. }
  11. public setModel(model: typeof ApiResource) {
  12. this._model = model
  13. }
  14. public getRelations() {
  15. return this.relations
  16. }
  17. /**
  18. * Fix the 'Cannot stringify arbitrary non-POJOs' warning, meaning server can not parse the store
  19. *
  20. * @see https://github.com/vuex-orm/vuex-orm/issues/255#issuecomment-876378684
  21. */
  22. toJSON () {
  23. return { ...this }
  24. }
  25. /**
  26. * Is it a newly created entity?
  27. *
  28. * If it is, it means this entity does not exist in the data source and that it has a temporary id
  29. */
  30. public isNew(): boolean {
  31. return !this.id || (typeof this.id === 'string' && this.id.slice(0, 3) === 'tmp')
  32. }
  33. /**
  34. * Get the IRI of the Entity
  35. *
  36. * @see https://api-platform.com/docs/admin/handling-relations/
  37. */
  38. public getIRI() {
  39. return `/api/${this.entity}/${this.id}`
  40. }
  41. }
  42. export default ApiResource