Browse Source

Set query param arrays/objects properly in Try It Out

shalvah 4 years ago
parent
commit
a507945c4d
1 changed files with 20 additions and 1 deletions
  1. 20 1
      resources/js/tryitout.js

+ 20 - 1
resources/js/tryitout.js

@@ -59,8 +59,27 @@ function makeAPICall(method, path, body, query, headers) {
     }
 
     const url = new URL(window.baseUrl + '/' + path.replace(/^\//, ''));
+
+    // We need this function because if you try to set an array or object directly to a URLSearchParams object,
+    // you'll get [object Object] or the array.toString()
+    function addItemToSearchParamsObject(key, value, searchParams) {
+            if (Array.isArray(value)) {
+                value.forEach((v, i) => {
+                    // Append {filters: [first, second]} as filters[0]=first&filters[1]second
+                    addItemToSearchParamsObject(key + '[' + i + ']', v, searchParams);
+                })
+            } else if (typeof value === 'object' && value !== null) {
+                Object.keys(value).forEach((i) => {
+                    // Append {filters: {name: first}} as filters[name]=first
+                    addItemToSearchParamsObject(key + '[' + i + ']', value[i], searchParams);
+                });
+            } else {
+                searchParams.append(key, value);
+            }
+    }
+
     Object.keys(query)
-        .forEach(key => url.searchParams.append(key, query[key]));
+        .forEach(key => addItemToSearchParamsObject(key, query[key], url.searchParams));
 
     return fetch(url, {
         method,