@@ -11,12 +11,13 @@ const { beautify } = require('../utils');
1111 * @typedef RESTConfig
1212 * @type {object }
1313 * @prop {string } [endpoint] - API base URL
14- * @prop {boolean } [prettyPrintJson=false] - pretty print json for response/request on console logs
15- * @prop {number } [timeout=1000] - timeout for requests in milliseconds. 10000ms by default
16- * @prop {object } [defaultHeaders] - a list of default headers
14+ * @prop {boolean } [prettyPrintJson=false] - pretty print json for response/request on console logs.
15+ * @prop {boolean } [printCurl=false] - print cURL request on console logs. False by default.
16+ * @prop {number } [timeout=1000] - timeout for requests in milliseconds. 10000ms by default.
17+ * @prop {object } [defaultHeaders] - a list of default headers.
1718 * @prop {object } [httpAgent] - create an agent with SSL certificate
18- * @prop {function } [onRequest] - a async function which can update request object.
19- * @prop {function } [onResponse] - a async function which can update response object.
19+ * @prop {function } [onRequest] - an async function which can update request object.
20+ * @prop {function } [onResponse] - an async function which can update response object.
2021 * @prop {number } [maxUploadFileSize] - set the max content file size in MB when performing api calls.
2122 */
2223const config = { } ;
@@ -42,6 +43,7 @@ const config = {};
4243 * }
4344 *}
4445 * ```
46+ *
4547 * With httpAgent
4648 *
4749 * ```js
@@ -192,6 +194,9 @@ class REST extends Helper {
192194 }
193195
194196 this . options . prettyPrintJson ? this . debugSection ( 'Request' , beautify ( JSON . stringify ( _debugRequest ) ) ) : this . debugSection ( 'Request' , JSON . stringify ( _debugRequest ) ) ;
197+ if ( this . options . printCurl ) {
198+ this . debugSection ( 'CURL Request' , curlize ( request ) ) ;
199+ }
195200
196201 let response ;
197202 try {
@@ -372,3 +377,23 @@ class REST extends Helper {
372377 }
373378}
374379module . exports = REST ;
380+
381+ function curlize ( request ) {
382+ if ( request . data ?. constructor . name . toLowerCase ( ) === 'formdata' ) return 'cURL is not printed as the request body is not a JSON' ;
383+ let curl = `curl --location --request ${ request . method ? request . method . toUpperCase ( ) : 'GET' } ${ request . baseURL } ` . replace ( "'" , '' ) ;
384+
385+ if ( request . headers ) {
386+ Object . entries ( request . headers ) . forEach ( ( [ key , value ] ) => {
387+ curl += `-H "${ key } : ${ value } " ` ;
388+ } ) ;
389+ }
390+
391+ if ( ! curl . toLowerCase ( ) . includes ( 'content-type: application/json' ) ) {
392+ curl += '-H "Content-Type: application/json" ' ;
393+ }
394+
395+ if ( request . data ) {
396+ curl += `-d '${ JSON . stringify ( request . data ) } '` ;
397+ }
398+ return curl ;
399+ }
0 commit comments