Skip to content

Instantly share code, notes, and snippets.

@gregdaynes
Last active August 6, 2016 05:37
Show Gist options
  • Select an option

  • Save gregdaynes/4f2b29c0b56f52fc8c04e3b2f71f580f to your computer and use it in GitHub Desktop.

Select an option

Save gregdaynes/4f2b29c0b56f52fc8c04e3b2f71f580f to your computer and use it in GitHub Desktop.
Fetch and reduce json data
// Transform JSON array of stats into object
// concat values into single strings for each key
// ----------------------------------------------
function transform(json) {
// iterate over each item in the JSON array
// replace null values with empty strings
// concat new value onto old value
return json.results.reduce(function(acc, data) {
return acc.then(prev => {
return {
one: (prev)
? `${prev.one},${data.one}`
: data.one,
two: (prev)
? `${prev.two},${data.two}`
: data.two,
three: (prev)
? `${prev.three},${data.three}`
: data.three,
};
});
}, Promise.resolve());
}
// Params for request, shouldn't need to modify this
// -------------------------------------------------
const options = {
headers: {
"Authorization": "Basic [base64 encoded hash]", // Add basic auth hash here
"Content-Type": "application/json; charset=utf-8",
},
}
// Configure endpoint to call
// --------------------------
const url = 'http://example.com';
const params = [
'key=value',
];
// Magic happens here, make request to endpoint
// 1: resolve body of response
// 2: pass body to transform function
// 4: return error if encountered
fetch(`${url}?${params.join('&')}`, options)
.then(res => res.json()) // [1]
.then(transform) // [2]
.catch(err => { throw new Error(err); }); // [4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment