Skip to content

Instantly share code, notes, and snippets.

@azaharafernandezguizan
Created November 25, 2021 09:26
Show Gist options
  • Save azaharafernandezguizan/a54c2a6e1f604a629f29b675b0fdd349 to your computer and use it in GitHub Desktop.
Save azaharafernandezguizan/a54c2a6e1f604a629f29b675b0fdd349 to your computer and use it in GitHub Desktop.
Archivo para utilizar Newman con dos colecciones de Postman
const newman = require('newman');
const fs = require('fs');
const collectionFileRoute = 'micoleccion.json';
const detailFileRoute = 'colecciondetalle.json';
const collectionFileRouteCreated = './sin/micoleccion_sinvariables.json';
const detailFileRouteCreated = './sin/colecciondetalle_sinvariables';
const commonNameForFiles = 'mi_api';
const arrayPropertyName = 'nombreObjetos';
const idPropertyName = 'id';
const variablesNamesToReplace = ['{{variable1}}','{{variable2}}', '{{num_pag}}', '{{num_results}}'];
const valuesToReplace = ['VALOR',’VALOR2, '0', '20'];
const idVariableNameToReplace = '{{id}}';
readCollectionFiles(null, collectionFileRoute, collectionFileRouteCreated);
function readCollectionFiles(idReceived, fromFile, toFile){
fs.readFile(fromFile, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = replaceVariablesAllSearch(data, idReceived);
fs.writeFile(toFile, result, function (err) {
if (err) {
return console.log(err);
}
newman.run({
collection: require('./' + toFile),
reporters: 'cli',
insecure: true,
}).on('request', function (error, args) {
if (error) {
console.error(error);
}
else {
var currentFileName = idReceived != null ? './created/'+ idReceived + '_' : './created/';
; currentFileName += commonNameForFiles + '_'+ args.item.name + '.json';
fs.writeFile(currentFileName, args.response.stream + "\r\n", function (error) {
console.log('File ' + currentFileName );
if (error) {
console.error(error);
}
else {
console.log('Creado correctamente');
if(idReceived == null){
getListAndFindId(args.response.stream);
}
}
});
}
});
});
});
}
function replaceVariablesAllSearch(data, idReceived){
var result = data;
for( var i=0; i < variablesNamesToReplace.length; i++){
result = result.replace(new RegExp(variablesNamesToReplace[i], 'g'), valuesToReplace[i]);
}
if(idReceived != null){
result = result.replace(new RegExp(idVariableNameToReplace, 'g'), idReceived);
}
return result;
}
function getListAndFindId(stream){
console.log('buscando ids');
let results = JSON.parse(stream);
console.log('Parseado: '+ results);
let list = results[arrayPropertyName];
console.log('Lista: '+list);
list.forEach(element => {
let currentId = element[idPropertyName];
readDetail(currentId);
});
}
function readDetail(idReceived){
console.log('readed id' + idReceived);
var fileForThisId = detailFileRouteCreated+'_'+idReceived+'.json';
readCollectionFiles(idReceived, detailFileRoute, fileForThisId);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment