decorators.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  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. // eslint-disable-next-line @typescript-eslint/ban-types
  12. return (target: object, propertyKey: string | symbol) => {
  13. // @ts-expect-error The object is an ApiResource
  14. const self = target.$self()
  15. self.addIriEncodedField(propertyKey as string, apiResource)
  16. }
  17. }
  18. /**
  19. * Decorates an ApiResource's property to signal it as a field that is provided
  20. * as an unique identifier by the API
  21. *
  22. * If the property is decorated, the HydraNormalizer will get the item[idField] value to hydrate
  23. * the id property of the instance
  24. */
  25. export function IdField(): PropertyDecorator {
  26. // We have to comply with the PropertyDecorator return type
  27. // eslint-disable-next-line @typescript-eslint/ban-types
  28. return (target: object, propertyKey: string | symbol) => {
  29. // @ts-expect-error The object is an ApiResource
  30. const self = target.$self()
  31. self.setIdField(propertyKey as string)
  32. }
  33. }