hydraNormalizer.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import {AnyJson} from "~/types/data";
  2. import ApiResource from "~/models/ApiResource";
  3. import {isArray, isNumber} from "lodash";
  4. import UrlUtils from "~/services/utils/urlUtils";
  5. /**
  6. * Normalisation du format de données Hydra
  7. */
  8. class HydraNormalizer {
  9. public static normalizeEntity(entity: ApiResource): AnyJson {
  10. const prototype = Object.getPrototypeOf(entity)
  11. const relations = prototype.constructor.relations
  12. for (const field in relations) {
  13. const value = entity[field]
  14. if (!isArray(value)) {
  15. console.warn("A model's relation is not an array")
  16. continue
  17. }
  18. const targetEntity = relations[field].entity
  19. entity[field] = value.map((id: number | string) => {
  20. if (!isNumber(id)) {
  21. throw Error(field + ' : invalid id')
  22. }
  23. return UrlUtils.makeIRI(targetEntity, id)
  24. })
  25. }
  26. return entity.$toJson()
  27. }
  28. }
  29. export default HydraNormalizer