Last active
September 24, 2016 00:16
-
-
Save ziprandom/55a1946457ebb29ab5bbd651975ba186 to your computer and use it in GitHub Desktop.
Superagent: Send JSON Object Alongside Files by Flatten the JSON Keys to HTML Form Names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import request from 'superagent'; | |
/* | |
* given files is an array of File Objects: | |
* | |
* sendAsHtmlForm("/api/posts", | |
* "post", {title: "a title", body. "a body"}, files) | |
* | |
*/ | |
function sendAsHtmlForm(url, method, json, files) { | |
let theRequest = request.post(url) | |
// a hack for laravel 4.2 controllers | |
// not recognizing form puts | |
if (method == "put") { | |
theRequest = theRequest.field('_method', 'put'); | |
} | |
// add files | |
files.forEach( | |
(attachment, index) => theRequest.attach(`${index}`, attachment) | |
); | |
// flatten json to html form names | |
toFormFields(entity.toJSON()).forEach( | |
([field, value]) => value ? theRequest.field(field, value) : null | |
); | |
return the_request.send(); | |
}; | |
function toFormFields(json, prefix = "") { | |
if ( | |
Object.prototype.toString.call( json ) === '[object Array]' | |
) { | |
return json.reduce( | |
(all, elem, index) => all.concat(toFormFields(elem, prefix + `[${index}]`)), [] | |
) | |
} else if (Object.prototype.toString.call( json ) === '[object Object]') { | |
return Object.keys(json).reduce( | |
(all, key) => all.concat(toFormFields(json[key], prefix ? prefix + `[${key}]` : `${key}`)), [] | |
); | |
} else { | |
return [[prefix, json]] | |
} | |
}; | |
module.exports(sendAsHtmlForm); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment