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.

Revisions

  1. gregdaynes revised this gist Aug 6, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion promise-reduce.js
    Original file line number Diff line number Diff line change
    @@ -33,7 +33,7 @@ const options = {

    // Configure endpoint to call
    // --------------------------
    const url = 'https://stats-api.ringpartner.com/stats/dp';
    const url = 'http://example.com';
    const params = [
    'key=value',
    ];
  2. gregdaynes created this gist Aug 6, 2016.
    48 changes: 48 additions & 0 deletions promise-reduce.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    // 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 = 'https://stats-api.ringpartner.com/stats/dp';
    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]