decorators.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import type ApiResource from '~/models/ApiResource'
  2. /**
  3. * Decorates an ApiResource's property to signal it as a field that is provided
  4. * as an IRI or an array of IRI by the API
  5. *
  6. * If the property is decorated, the HydraNormalizer will parse the IRI when de-normalizing
  7. * to get the id(s), then re-encode it as IRI(s) when re-normalizing.
  8. */
  9. export function IriEncoded(apiResource: typeof ApiResource): PropertyDecorator {
  10. // We have to comply with the PropertyDecorator return type
  11. return (target: object, propertyKey: string | symbol) => {
  12. // @ts-expect-error The object is an ApiResource
  13. const self = target.$self()
  14. self.addIriEncodedField(propertyKey as string, apiResource)
  15. }
  16. }
  17. /**
  18. * Decorates an ApiResource's property to signal it as a field that is provided
  19. * as an unique identifier by the API
  20. *
  21. * If the property is decorated, the HydraNormalizer will get the item[idField] value to hydrate
  22. * the id property of the instance
  23. */
  24. export function IdField(): PropertyDecorator {
  25. // We have to comply with the PropertyDecorator return type
  26. return (target: object, propertyKey: string | symbol) => {
  27. // @ts-expect-error The object is an ApiResource
  28. const self = target.$self()
  29. self.setIdField(propertyKey as string)
  30. }
  31. }
  32. export function Assert(assert: object): PropertyDecorator {
  33. // We have to comply with the PropertyDecorator return type
  34. return (target: object, propertyKey: string | symbol) => {
  35. // @ts-expect-error The object is an ApiResource
  36. const self = target.$self()
  37. const rules = self.getAsserts()
  38. rules[propertyKey] = assert
  39. self.setAsserts(rules)
  40. }
  41. }
  42. /**
  43. *
  44. * @constructor
  45. */
  46. export function IdLess(): ClassDecorator {
  47. // We have to comply with the PropertyDecorator return type
  48. return (target) => {
  49. // @ts-expect-error The object is an ApiResource Class
  50. target.setIdLess()
  51. }
  52. }