Skip to content

Instantly share code, notes, and snippets.

@romanlex
Last active June 4, 2018 11:33
Show Gist options
  • Save romanlex/72763543776cb7b1ac935b12e030d865 to your computer and use it in GitHub Desktop.
Save romanlex/72763543776cb7b1ac935b12e030d865 to your computer and use it in GitHub Desktop.
Fetch multiple urls with fetch and save multiple response data
const RAW_CONTENT_TYPES = ['image/svg+xml']
/**
* Fetch url
*
* @param {string} url
*/
export const fetchResources = url => fetch(url, {
credentials: 'same-origin',
}).then((response) => {
if (!response.ok) {
throw new Error(`Could load resource from ${url}: ${response.statusText}`)
}
return response
})
.then((response) => {
const contentType = response.headers.get('Content-Type')
const responseClone = response.clone()
const promises = []
promises.push(response.url)
promises.push(contentType)
promises.push(response.arrayBuffer())
if (RAW_CONTENT_TYPES.includes(contentType)) {
promises.push(responseClone.text())
}
return Promise.all(promises)
})
/**
* Build object with response data
*
* @param {Array<Array>} responses array of responses
*/
const buildContentResponse = responses => responses.reduce((acc, response) => {
let data = {
url: response[0],
contentType: response[1],
content: response[2],
}
if (response[3]) {
data = {
...data,
rawString: response[3],
}
}
return [...acc, { ...data }]
}, [])
/**
* Load external resources
*
* @param {Array} externalResources array of urls
*/
export const fetchExternalResources = externalResources =>
Promise.all(externalResources.map(url => fetchResources(url)))
.then(responses => buildContentResponse(responses))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment