hydraParser.ts 2.4 KB

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