Skip to content

Commit 5be8b90

Browse files
authored
Merge pull request #281 from mbrodala/vue-fetch-params
Respect fetch params in Vue template
2 parents eef2629 + bc222a4 commit 5be8b90

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

templates/vue/utils/fetch.js

+15
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ const transformRelationToIri = (payload) => {
1616
return payload;
1717
};
1818

19+
const makeParamArray = (key, arr) =>
20+
arr.map(val => `${key}[]=${val}`).join('&');
21+
1922
export default function(id, options = {}) {
2023
if ('undefined' === typeof options.headers) options.headers = new Headers();
2124

@@ -33,6 +36,18 @@ export default function(id, options = {}) {
3336
if (isObject(payload) && payload['@id'])
3437
options.body = JSON.stringify(transformRelationToIri(payload));
3538

39+
if (options.params) {
40+
const params = normalize(options.params);
41+
let queryString = Object.keys(params)
42+
.map(key =>
43+
Array.isArray(params[key])
44+
? makeParamArray(key, params[key])
45+
: `${key}=${params[key]}`
46+
)
47+
.join('&');
48+
id = `${id}?${queryString}`;
49+
}
50+
3651
return global.fetch(new URL(id, ENTRYPOINT), options).then(response => {
3752
if (response.ok) return response;
3853

templates/vue/utils/hydra.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import get from 'lodash/get';
2+
import has from 'lodash/has';
3+
import mapValues from 'lodash/mapValues';
4+
5+
export function normalize(data) {
6+
if (has(data, 'hydra:member')) {
7+
// Normalize items in collections
8+
data['hydra:member'] = data['hydra:member'].map(item => normalize(item));
9+
10+
return data;
11+
}
12+
13+
// Flatten nested documents
14+
return mapValues(data, value =>
15+
Array.isArray(value)
16+
? value.map(v => get(v, '@id', v))
17+
: get(value, '@id', value)
18+
);
19+
}

0 commit comments

Comments
 (0)