hydra.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. export default {
  2. parse(response) {
  3. if (response['hydra:member']) {
  4. response.totalCount = response['hydra:totalItems'];
  5. return this.parseCollection(response);
  6. } else {
  7. return this.parseItem(response);
  8. }
  9. },
  10. populateId(data) {
  11. if (data['@id'] && data['@id'] instanceof String) {
  12. var iriParts = data['@id'].split('/');
  13. data.id = iriParts[iriParts.length - 1];
  14. }
  15. },
  16. populateAllData(data) {
  17. this.populateId(data);
  18. for (const key in data) {
  19. const value = data[key];
  20. if (value instanceof Object) {
  21. this.populateAllData(value);
  22. }
  23. }
  24. },
  25. parseItem(data) {
  26. this.populateId(data);
  27. if (data['hydra:previous']) {
  28. let iriParts = data['hydra:previous'].split('/');
  29. data.previous = iriParts[iriParts.length - 1];
  30. }
  31. if (data['hydra:next']) {
  32. let iriParts = data['hydra:next'].split('/');
  33. data.next = iriParts[iriParts.length - 1];
  34. }
  35. if (data['hydra:totalItems']) {
  36. data.totalItems = data['hydra:totalItems'];
  37. }
  38. if (data['hydra:itemPosition']) {
  39. data.itemPosition = data['hydra:itemPosition'];
  40. }
  41. return data;
  42. },
  43. parseCollection(data) {
  44. let collectionResponse = data['hydra:member'];
  45. collectionResponse.metadata = {};
  46. collectionResponse.order = {};
  47. collectionResponse.search = {};
  48. // Put metadata in a property of the collection
  49. for (const key in data) {
  50. const value = data[key];
  51. if ('hydra:member' !== key) {
  52. collectionResponse.metadata[key] = value;
  53. }
  54. }
  55. // Populate href property for all elements of the collection
  56. for (const key in collectionResponse) {
  57. const value = collectionResponse[key];
  58. this.populateAllData(value);
  59. }
  60. if ('undefined' !== typeof (data['hydra:search'])) {
  61. let collectionSearch = data['hydra:search']['hydra:mapping'];
  62. for (const key in collectionSearch) {
  63. const value = collectionSearch[key];
  64. if (value['variable'].indexOf("filter[order]") === 0) {
  65. collectionResponse.order[value['property']] = value;
  66. } else if (value['variable'].indexOf("filter[where]") === 0) {
  67. collectionResponse.search[value['property']] = value;
  68. }
  69. }
  70. }
  71. return collectionResponse;
  72. }
  73. }