Skip to content

Commit

Permalink
Merge pull request #281 from mbrodala/vue-fetch-params
Browse files Browse the repository at this point in the history
Respect fetch params in Vue template
  • Loading branch information
alOneh authored Mar 26, 2021
2 parents eef2629 + bc222a4 commit 5be8b90
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
15 changes: 15 additions & 0 deletions templates/vue/utils/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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;

Expand Down
19 changes: 19 additions & 0 deletions templates/vue/utils/hydra.js
Original file line number Diff line number Diff line change
@@ -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)
);
}

0 comments on commit 5be8b90

Please sign in to comment.