Skip to content

Respect fetch params in Vue template #281

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
);
}