| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- import {AnyJson} from "~/types/types";
- export default class HydraParser {
- constructor() {
- }
- parse(response: AnyJson): AnyJson {
- if (response['hydra:member']) {
- response.totalCount = response['hydra:totalItems'];
- return this.parseCollection(response);
- } else {
- return this.parseItem(response);
- }
- }
- populateId(data: AnyJson) {
- if (data['@id'] && data['@id'] instanceof String) {
- var iriParts = data['@id'].split('/');
- data.id = iriParts[iriParts.length - 1];
- }
- }
- populateAllData(data: AnyJson):void {
- this.populateId(data);
- for (const key in data) {
- const value = data[key];
- if (value instanceof Object) {
- this.populateAllData(value);
- }
- }
- }
- parseItem(data: AnyJson): AnyJson {
- this.populateId(data);
- if (data['hydra:previous']) {
- let iriParts = data['hydra:previous'].split('/');
- data.previous = iriParts[iriParts.length - 1];
- }
- if (data['hydra:next']) {
- let iriParts = data['hydra:next'].split('/');
- data.next = iriParts[iriParts.length - 1];
- }
- if (data['hydra:totalItems']) {
- data.totalItems = data['hydra:totalItems'];
- }
- if (data['hydra:itemPosition']) {
- data.itemPosition = data['hydra:itemPosition'];
- }
- return data;
- }
- parseCollection(data: AnyJson): AnyJson {
- let collectionResponse = data['hydra:member'];
- collectionResponse.metadata = {};
- collectionResponse.order = {};
- collectionResponse.search = {};
- // Put metadata in a property of the collection
- for (const key in data) {
- const value = data[key];
- if ('hydra:member' !== key) {
- collectionResponse.metadata[key] = value;
- }
- }
- // Populate href property for all elements of the collection
- for (const key in collectionResponse) {
- const value = collectionResponse[key];
- this.populateAllData(value);
- }
- if ('undefined' !== typeof (data['hydra:search'])) {
- let collectionSearch = data['hydra:search']['hydra:mapping'];
- for (const key in collectionSearch) {
- const value = collectionSearch[key];
- if (value['variable'].indexOf("filter[order]") === 0) {
- collectionResponse.order[value['property']] = value;
- } else if (value['variable'].indexOf("filter[where]") === 0) {
- collectionResponse.search[value['property']] = value;
- }
- }
- }
- return collectionResponse;
- }
- }
|