Skip to content

Instantly share code, notes, and snippets.

@jaimeagudo
Last active July 4, 2023 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaimeagudo/49683e1f61eddfd79fcadde012dd7d4b to your computer and use it in GitHub Desktop.
Save jaimeagudo/49683e1f61eddfd79fcadde012dd7d4b to your computer and use it in GitHub Desktop.
/**
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