From bc222a4aec9acde98b8aaf432508e667c857889c Mon Sep 17 00:00:00 2001 From: Mathias Brodala Date: Thu, 25 Mar 2021 17:06:16 +0100 Subject: [PATCH] Respect fetch params in Vue template This is a plain copy from the vue-common template. --- templates/vue/utils/fetch.js | 15 +++++++++++++++ templates/vue/utils/hydra.js | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 templates/vue/utils/hydra.js diff --git a/templates/vue/utils/fetch.js b/templates/vue/utils/fetch.js index 14dafb65..ee102499 100644 --- a/templates/vue/utils/fetch.js +++ b/templates/vue/utils/fetch.js @@ -16,6 +16,9 @@ const transformRelationToIri = (payload) => { return payload; }; +const makeParamArray = (key, arr) => + arr.map(val => `${key}[]=${val}`).join('&'); + export default function(id, options = {}) { if ('undefined' === typeof options.headers) options.headers = new Headers(); @@ -33,6 +36,18 @@ export default function(id, options = {}) { if (isObject(payload) && payload['@id']) options.body = JSON.stringify(transformRelationToIri(payload)); + if (options.params) { + const params = normalize(options.params); + let queryString = Object.keys(params) + .map(key => + Array.isArray(params[key]) + ? makeParamArray(key, params[key]) + : `${key}=${params[key]}` + ) + .join('&'); + id = `${id}?${queryString}`; + } + return global.fetch(new URL(id, ENTRYPOINT), options).then(response => { if (response.ok) return response; diff --git a/templates/vue/utils/hydra.js b/templates/vue/utils/hydra.js new file mode 100644 index 00000000..6d23ee75 --- /dev/null +++ b/templates/vue/utils/hydra.js @@ -0,0 +1,19 @@ +import get from 'lodash/get'; +import has from 'lodash/has'; +import mapValues from 'lodash/mapValues'; + +export function normalize(data) { + if (has(data, 'hydra:member')) { + // Normalize items in collections + data['hydra:member'] = data['hydra:member'].map(item => normalize(item)); + + return data; + } + + // Flatten nested documents + return mapValues(data, value => + Array.isArray(value) + ? value.map(v => get(v, '@id', v)) + : get(value, '@id', value) + ); +}