How to capture responsebody from newman - newman

I want to capture the responsebody in Newman.
const newman = require('newman');
newman.run({
collection: require('./xxx.json'),
iterationData: './data.jsp',
reporters: 'cli'
}, function (err, summary) {
if (err) { throw err; }
console.log('collection run complete!');
console.log(summary);
});
I use the code above. it works fine but I want to capture the json output here from the call. How can I achieve it?

Perhaps you used a wrong term for retrieving json response body. If you want to just get the response body you need to parse JSON returned and to save it to a variable.
If you would use newman to run through command line there are everything is super simple:
let body = JSON.parse(responseBody)
console.log(body)
and after test where you need to see the response you put this 2 lines of code.
But with your case perhaps you need that:
1) Callback option
const newman = require('newman');
newman.run({
collection: require('./xxx.json'),
iterationData: './data.jsp',
reporters: 'cli'
}, function (err, summary) {
if (err) { throw err; }
console.log('collection run complete!');
console.log(summary);
})
.on('request', function (err, data) {
// err, data can be used to write to files using the node fs module.
});
or the better and modern option:
let response = await newman.run({
collection: 'collection',
environment: 'env',
})
.on('request', async function (err, data) {
// err, data can be used to write to files using the node fs module.
});
console.log(response)
Not sure I will be working as expected, but at least try.
Btw, where do you run these tests? just in clear env or use some runner framework.

Postman return execution summary in Callback function. after execution if you save the summary in callback and return it. you can access request/response/ headers.
function runcollection(callback){
newman.run({
collection: 'C:\\newman\\PMP Dependency latest collection\\Updated\\TestCollection.postman_collection.json',
environment: 'C:\\newman\\PMP Dependency latest collection\\Updated\\Test.postman_environment.json',
iterationCount :1
},function(error, summary){
callback(summary)
});
}
runcollection(result => {console.log(result.run.executions[0].response.stream.toString())});

Related

NestJs Multer upload file with fileFilter cause infinite pending

i have an issue witch Multer and NestJS to upload file. I try to check if file already exist to return an error. it's working well but if i try to re-upload a file after that, i have infinite pending request. (if i remove the filter i have no problem but i overwrite the file)
here my controller code:
#UseGuards(JwtAuthGuard)
#UseGuards(RolesGuard)
#Role('SCENARISTE')
#Post('upload/sound')
#UseInterceptors(FileInterceptor('file', {
storage: diskStorage({
destination: 'files/sounds',
filename: function (req, file, callback) {
return callback(null, file.originalname);
}
}),
fileFilter: (req, file, callback) => {
if (existsSync(join('files/sounds', file.originalname))) {
return callback(new NotAcceptableException(ErrorType.FILE_ALREADY_EXIST), false);
} else {
return callback(null, true);
}
},
}))
uploadSound(#UploadedFile() file: Express.Multer.File) {
const fileReponse = {
originalname: file.originalname,
mimetype: file.mimetype,
filename: file.filename,
size: file.size,
destination: file.destination,
fieldname: file.fieldname,
path: file.path
};
return fileReponse;
}
thank in advance for your help
may be the first request not close/stop correctly ?
According to Multer's documantion, whenever you want to throw an error, you must call the callback by passing the first argument with an error, and leave the second argument or pass the false value.
Hence, try to change your code like this:
return callback(new NotAcceptableException(ErrorType.FILE_ALREADY_EXIST));

How to retrieve JSON object stored in cache from service worker?

I have a Json object stored in cache , Please see my cache here.
And I want to retrieve the json values from my service worker
caches.open('my-post-request').then(function (cache) {
cache.match('/cached-products.json').then(function (matchedResponse) {
return fetch('/cached-products.json').then(function (response) {
return response;
})
});
});
is there a way to do that? exploring the response in the console I can just see the properties headers, ok, status, type, url, body, but I cant find my json values anywhere.
I would appreciate any suggestion.
Thanks
You could try something like this:
var CACHE_NAME = 'dependencies-cache';
self.addEventListener('install', function(event) {
console.log('[install] Kicking off service worker registration!');
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) { // With the cache opened, load a JSON file containing an array of files to be cached
return fetch('files-to-cache.json').then(function(response) {
return response.json(); // Once the contents are loaded, convert the raw text to a JavaScript object
}).then(function(files) {
console.log('[install] Adding files from JSON file: ', files); // this will log the cached json file
return cache.addAll(files); // Use cache.addAll just as you would a hardcoded array of items
});
})
.then(function() {
console.log(
'[install] All required resources have been cached;',
'the Service Worker was successfully installed!'
);
return self.skipWaiting(); // Force activation
})
);
});
This will solve your problem.
From the code above, you can simply return your response as response.json() to convert the raw text to a Javascript Object. For full implementation of Service Worker to cache JSON file, you can visit this documentation.

Amazon Lex- slot elicitation not working inside callback

I have a call back function which is getting data from an external API and depends on a data check I have tried for a slot elicitation inside callback but looks like elicitation is not working inside the callback. Please find the code snippet below,
GetCustomerDetails().then(response => {
var serializedcustomerDetails = convert.xml2json(response.data, {
compact: true,
spaces: 2
});
var customerDetails = JSON.parse(serializedcustomerDetails);
let filteredCustomerDetails = _.filter(customerDetails.CustomerInfo.CustomerDetails, function (o) {
return o.CustomerName._text.includes(customerName);
})
if (filteredCustomerDetails.length == 1) {
callback(elicitSlot(outputSessionAttributes, intentRequest.currentIntent.name,
intentRequest.currentIntent.slots, '​CustomerCode', {
contentType: 'PlainText',
content: `Do you mean ${filteredCustomerDetails[0].CustomerName._text} of ${filteredCustomerDetails[0].SpecialityName._text} department?`
}));
return;
}
}).catch(error => {
console.log(`${error}`)
})
This is my first Awnser on stack so please bear with me.
I have come accross the same problem in a recent project and there are a few things that you can check.
How long does the API call take?
If your API call takes a long time it will be worth checking the timeout settings on your Lambda function. AWS Console -> Lambda -> Your Function -> Basic settings -> Timeout.
Does your Lambda function finish before the API call is done?
I fixed this issue by building a node module to handle my business logic, the module has a function called getNextSlot it returns as a Promise. Inside this function I check the incoming event and figure out which slot I need to elicit next, part of my flow is to call an API endpoint that takes around 10 seconds to complete.
I use the request-promise package to make the api call, this node module makes sure that the lambda function keeps running while the call is running.
exports.getData = function (url, data) {
var pr = require("request-promise");
var options = {
method: 'POST',
url: 'api.example',
qs: {},
headers:
{
'Content-Type': 'application/json'
},
body: {
"example": data
},
json: true,
timeout: 60000
};
return pr(options);
}
In my main code I call this function as:
apiModule.getData("test", "data")
.then(function (data) {
//Execute callback
})
.catch(function (error) {
console.log(error);
reject(error);
});
This solved the issue for me anyways.
Thanks,

What is the mechanism to incorporate send and download postman option from within Newman call

What is the mechanism to incorporate send and download postman option from within Newman call?
Output of my REST call is file (image/binary). On running with Newman I don't see the output. Is there any way to save the contents in a file.
as of now newman do not have this feature. but you can have a workaround where you can read the output stream and write it into the file at desired location .
attaching sample code :
var i = 0,
fs = require('fs'),
newman = require('newman'); // ensure that you have run "npm i newman" in the same directory as this file
newman.run({
// run options go here
}, function (err, summary) {
// handle collection run err, process the run summary here
}).on('request', function (err, execution) { // This is triggered when a response has been recieved
if (err) { return console.error(err); }
fs.writeFile(`response${i++}.txt`, execution.response.stream, function (error) {
if (error) { console.error(error); }
});
});

How to run terminal commands using Dart HttpRequest?

I need to send a request to the server to run a jar file with a string argument/parameter and return the results as a string.
On server side you can run a process and send result back like this :
HttpServer.bind(InternetAddress.ANY_IP_V4, 3031).then((server) {
server.listen((HttpRequest request) {
var param = request.uri.queryParameters['name'];
Process.run('java', ['-jar', 'myJar.jar', param]).then((pr) =>
request.response
..write(pr.stdout)
..close()
);
});
});

Resources