Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(rest): print curl #4396

Merged
merged 4 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions docs/helpers/REST.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@ Type: [object][4]
### Properties

- `endpoint` **[string][3]?** API base URL
- `prettyPrintJson` **[boolean][6]?** pretty print json for response/request on console logs
- `timeout` **[number][5]?** timeout for requests in milliseconds. 10000ms by default
- `defaultHeaders` **[object][4]?** a list of default headers
- `prettyPrintJson` **[boolean][6]?** pretty print json for response/request on console logs.
- `printCurl` **[boolean][6]?** print cURL request on console logs. False by default.
- `timeout` **[number][5]?** timeout for requests in milliseconds. 10000ms by default.
- `defaultHeaders` **[object][4]?** a list of default headers.
- `httpAgent` **[object][4]?** create an agent with SSL certificate
- `onRequest` **[function][7]?** a async function which can update request object.
- `onResponse` **[function][7]?** a async function which can update response object.
- `onRequest` **[function][7]?** an async function which can update request object.
- `onResponse` **[function][7]?** an async function which can update response object.
- `maxUploadFileSize` **[number][5]?** set the max content file size in MB when performing api calls.


Expand Down
35 changes: 30 additions & 5 deletions lib/helper/REST.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ const { beautify } = require('../utils');
* @typedef RESTConfig
* @type {object}
* @prop {string} [endpoint] - API base URL
* @prop {boolean} [prettyPrintJson=false] - pretty print json for response/request on console logs
* @prop {number} [timeout=1000] - timeout for requests in milliseconds. 10000ms by default
* @prop {object} [defaultHeaders] - a list of default headers
* @prop {boolean} [prettyPrintJson=false] - pretty print json for response/request on console logs.
* @prop {boolean} [printCurl=false] - print cURL request on console logs. False by default.
* @prop {number} [timeout=1000] - timeout for requests in milliseconds. 10000ms by default.
* @prop {object} [defaultHeaders] - a list of default headers.
* @prop {object} [httpAgent] - create an agent with SSL certificate
* @prop {function} [onRequest] - a async function which can update request object.
* @prop {function} [onResponse] - a async function which can update response object.
* @prop {function} [onRequest] - an async function which can update request object.
* @prop {function} [onResponse] - an async function which can update response object.
* @prop {number} [maxUploadFileSize] - set the max content file size in MB when performing api calls.
*/
const config = {};
Expand All @@ -42,6 +43,7 @@ const config = {};
* }
*}
* ```
*
* With httpAgent
*
* ```js
Expand Down Expand Up @@ -192,6 +194,9 @@ class REST extends Helper {
}

this.options.prettyPrintJson ? this.debugSection('Request', beautify(JSON.stringify(_debugRequest))) : this.debugSection('Request', JSON.stringify(_debugRequest));
if (this.options.printCurl) {
this.debugSection('CURL Request', curlize(request));
}

let response;
try {
Expand Down Expand Up @@ -372,3 +377,23 @@ class REST extends Helper {
}
}
module.exports = REST;

function curlize(request) {
if (request.data?.constructor.name.toLowerCase() === 'formdata') return 'cURL is not printed as the request body is not a JSON';
let curl = `curl --location --request ${request.method ? request.method.toUpperCase() : 'GET'} ${request.baseURL} `.replace("'", '');

if (request.headers) {
Object.entries(request.headers).forEach(([key, value]) => {
curl += `-H "${key}: ${value}" `;
});
}

if (!curl.toLowerCase().includes('content-type: application/json')) {
curl += '-H "Content-Type: application/json" ';
}

if (request.data) {
curl += `-d '${JSON.stringify(request.data)}'`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if data is not JSON? But encoded form?

Copy link
Collaborator Author

@kobenguyent kobenguyent Jun 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that won't be a problem with encoded form, the curl will look like this.

    › [CURL Request] curl --location --request POST https://httpbin.org/post -H "X-API-Key: apiKey-onRequest" -H "Content-Type: application/json" -d '{"_overheadLength":161,"_valueLength":0,"_valuesToMeasure":[{"fd":null,"path":"/Users/t/Desktop/projects/codeceptjs-rest-demo/src/fixtures/test_image.png","flags":"r","mode":438,"end":null,"bytesRead":0,"_events":{},"_readableState":{"highWaterMark":65536,"buffer":[],"bufferIndex":0,"length":0,"pipes":[],"awaitDrainWriters":null},"_eventsCount":3}],"writable":false,"readable":true,"dataSize":0,"maxDataSize":2097152,"pauseStreams":true,"_released":false,"_streams":["----------------------------917245260724904416987426\r\nContent-Disposition: form-data; name=\"attachment\"; filename=\"test_image.png\"\r\nContent-Type: image/png\r\n\r\n",{"source":{"fd":null,"path":"/Users/t/Desktop/projects/codeceptjs-rest-demo/src/fixtures/test_image.png","flags":"r","mode":438,"end":null,"bytesRead":0,"_events":{},"_readableState":{"highWaterMark":65536,"buffer":[],"bufferIndex":0,"length":0,"pipes":[],"awaitDrainWriters":null},"_eventsCount":3},"dataSize":0,"maxDataSize":null,"pauseStream":true,"_maxDataSizeExceeded":false,"_released":false,"_bufferedEvents":[{"0":"pause"}],"_events":{},"_eventsCount":1},null],"_currentStream":null,"_insideLoop":false,"_pendingNext":false,"_boundary":"--------------------------917245260724904416987426"}'

}
return curl;
}
Loading