Last active
July 4, 2023 09:04
-
-
Save jaimeagudo/49683e1f61eddfd79fcadde012dd7d4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Same signature as fetch. It returns a ready to use curl command with | |
{headers} optional JSON {body}, {method} and CLI {curlCliOptions} | |
curl('https://en.wikipedia.org/api/rest_v1/page/summary/Cehegin', | |
{ | |
headers: { accept: 'application/json' }, | |
body: {}, | |
method: 'GET' | |
}, | |
'-vvv' }); | |
*/ | |
const noUserAgent = h => !/User/i.test(h); | |
type Props = { | |
headers?: Headers | object; | |
method?: string; | |
body?: any; | |
}; | |
export const curl = (url: string, { headers, body = null, method = 'GET' }: Props, curlCliOptions = '') => { | |
let headerString = ''; | |
//@ts-ignore | |
if (headers?.forEach) { | |
//@ts-ignore | |
headers.forEach((value, headerKey) => { | |
headerString = noUserAgent(headerKey) ? headerString.concat(` -H '${headerKey}:${value}'`) : headerString; | |
}); | |
} else { | |
const headerKeys = headers ? Object.keys(headers).filter(noUserAgent) : []; | |
//@ts-ignore | |
headerString = headerKeys.reduce((s, headerKey) => `${s} -H ${headerKey}:${headers[headerKey]}`, ''); | |
} | |
const bodyArgs = body ? `-d ${JSON.stringify(body)}` : ''; | |
const command = `curl ${curlCliOptions} ${headerString} -X ${method} ${url} ${bodyArgs}`; | |
return `\n\n${command}\n\n\n`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment