Skip to content

Instantly share code, notes, and snippets.

@ManiaciaChao
Created March 12, 2020 06:43
Show Gist options
  • Save ManiaciaChao/e3be17489d8acbd98a269de7d35b1ea2 to your computer and use it in GitHub Desktop.
Save ManiaciaChao/e3be17489d8acbd98a269de7d35b1ea2 to your computer and use it in GitHub Desktop.
make `fetch` API compatible with deprecated `request` library
import { URLSearchParams } from 'url'
/**
* @description for Map<string, any> only
* @param {Map} map
*/
export const mapToObj = map =>
Array.from(map).reduce(
(obj, [key, value]) => Object.assign(obj, { [key]: value }),
{}
)
/**
*
* @param {Promise[]}} promises
*/
const success = promises => {
return Promise.all(
promises.map(p => {
return p.then(
val => Promise.reject(val),
err => Promise.resolve(err)
)
})
).then(
errors => Promise.reject(errors),
val => Promise.resolve(val)
)
}
export const requestCompat = fetch => async config => {
const { url, headers, method, followRedirect, form } = config
const options = {
method,
redirect: followRedirect ? 'follow' : 'manual',
headers,
}
if (form && method === 'POST') {
options.body = new URLSearchParams(form)
}
const resp = await fetch(url, options)
const body = await resp.text()
return {
request: { headers },
headers: mapToObj(resp.headers),
body,
statusCode:resp.status
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment