cloudflare / templates

A collection of starter templates and examples for Cloudflare Workers and Pages
https://cloudflareworkers.com
MIT License
1k stars 638 forks source link

Aggregate requests example should fetch bodies in parallel #4

Closed jrf0110 closed 1 year ago

jrf0110 commented 6 years ago

Currently, the aggregate requests example requests each body in series:

const btc = await btcResp.json()
const eth = await ethResp.json()
const ltc = await ltcResp.json()

This should be done all at once

Proposal 1

This would be a pretty minimal change:

const [btc, eth, ltc] = await Promise.all([btcResp, ethResp, ltcResp].map(res => res.json()))

Proposal 2

I kinda just went all out

// Make multiple requests, aggregate the responses and
// send it back as a single response.

const currencies = ['BTC', 'ETH', 'LTC']

addEventListener('fetch', event => {
    event.respondWith(fetchAndLog(event.request))
})

async function fetchAndLog(request) {
    const [btc, eth, ltc] = await Promise.all(
      currencies
        .map(currency => fetch(`https://api.coinbase.com/v2/prices/${currency}-USD/spot`))
        .map(p => p.then(res => res.json()))
        .map(p => p.then(({ data: { amount } }) => amount))
    )

    const body = { btc, eth, ltc }

    return new Response(JSON.stringify(body, null, 2), {
      status: 200,
      headers: {'Content-Type': 'application/json'}
    })
}
lauragift21 commented 1 year ago

Hello @jrf0110! This is very due for a response. Thanks for the recommendation to simplify the code. Closing this issue because this code has been updated.