Postman if/else condition not working properly - postman-testcase

This code is not working as expected when running collection and used as a test script on the first request:
when console.log gives output null, the collection doesn't stop, when it should.
function never goes to the 'else' condition, even when I force it by changing the GET results.
pm.test("Any?", function () {
var jsonData = pm.response.json();
if (pm.expect(jsonData.metadata.total_data).to.eql(0))
{console.log('null');
postman.setNextRequest(null);}
else
{console.log('Next request');
postman.setNextRequest('Name of Next request');}
});

Use a forEach and store the jsonData you want to check in a data array.
let checkingValues= [4,1,5,6,2];
checkingValues.forEach(() => {

Related

How to sequentially send requests to the server?

I have a List, and I need to send each element of this List to the server sequentially. And if the answer is with an error, then do not continue sending, but display an error. I am trying to use
await Future.wait([]);
but I do not quite understand how to complete the send on failure, and how to iterate over the elements.
To iterate over elements through .forEach(element) {}
The compiler throws an error: The argument type 'List' can't be assigned to the parameter type 'Iterable<Future>'
Here is what I am trying to do:
await Future.wait([
state.revisionFill.forEach((element) {
var successOrFail = await ContainerExpire.call(ContainerExpireParams(token: token, entity: element.entity));
})
]);
I'm new and don't fully understand async/sync requests in flutter. Tell me which direction to study.
How to complete the next send if it fails?
This seems to be what you're looking for:
for (var element in state.revisionFill) {
var successOrFail = await ContainerExpire.call(ContainerExpireParams(token: token, entity: element.entity));
if (successOrFail.hasFailed()) {
//add code for some possible error handling
break;
}
}
I am assuming that based on the value of successOrFail you can tell whether or not an error occured. Basically after each request you check for the status, and break on an error. You can add logic for displaying your error message.

when running expres programme get an load error page

var express = require('express');
var app = express();
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
books = require('./models/books.js');
mongoose.connect('mongodb://localhost/books');
var db = mongoose.connection;
app.get('/api/authors', function (req, res) {
books.getBooks(function (books,err) {
if(err){
throw err;
}
res.json(books);
});
});
Why we cannot use the function(err, books) as function(books, error).
I want to know what principle it violates.
When query is executed, results are passed as parameters to callback function. If If there is any error in executing the query, the error is passed as first argument and the results are passed as second parameter to the callback function. And this is how it works.
So, you can't use it interchangeably.
In your case books.getBooks(function (books,err) {.. if there is any error books will be the one containing in it. And if not, there will be results in err params.
And I assume your query is working OK and you are throwing error checking on err value that's why you see the error.
May be you are getting confused with the names of the params. Remember, they are just the variable names, results are there according to the position of variables in callback.
To answer your question on:
Why we cannot use the function(err, books) as function(books,
error).
Most npm modules follow the Continuation-passing style(CPS) design pattern, which uses:
cb(null, data) to pass on a successful result.
cb(err) to pass on an error and exit the function.
and, the function has only one outcome.
For example:
function getBooks(cb) {
let books, error;
// .... Perform the operations
// .... If all goes well store
// .... the results in books
if (books) {
cb(null, result);
} else {
error = "There was an error loading books"
cb(error)
}
}
This is not a complete example, but shows the essence of it.
TL;DR: That, my friend, is convention.
The only thing that I can think of without knowing the error is that you might want to use:
let books = mongoose.model ('Books');
And your model should be called Books.
Is it possible to include the Error message and Model so we could have some more info about the problem?

TypeError seneca indexof if not a function during respond

I have written a simple action which connects to mongo db using seneca-mongo store module, execute a list query and get the results. I can see that the query was successful and the correct results were fetched. When I try to send these results back to the client, the respond call errors out with following message and stack trace.
ERROR act root$ OUT cmd:getparams,role:diff 11 {cmd:getparams,role:diff,payload:{id:scalaScan}} ENTRY (dqk22) - seneca: Action cmd:getparams,role:diff callback threw: k.indexOf is not a function. act_callback {message:k.indexOf is not a function,pattern:cmd:getparams,role:diff,instance:Seneca/0.7.2/d0twcki9cmxg/1485517 TypeError: k.indexOf is not a function
at /scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:851:13
at Function.forEach (/scratch/DiffAnalyzer/node_modules/lodash/dist/lodash.js:3298:15)
at Object.defaultmodify [as modify] (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:850:7)
at respond (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:654:22)
at Seneca.<anonymous> (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:401:7)
at act_done (/scratch/DiffAnalyzer/node_modules/seneca/seneca.js:1554:16)
at /scratch/DiffAnalyzer/node_modules/gate-executor/gate-executor.js:127:20
at Seneca.<anonymous> (/scratch/DiffAnalyzer/analyze.js:613:5)
at act_done (/scratch/DiffAnalyzer/node_modules/seneca/seneca.js:1554:16)
at /scratch/DiffAnalyzer/node_modules/gate-executor/gate-executor.js:127:20
at /scratch/DiffAnalyzer/node_modules/seneca-mongo-store/mongo-store.js:329:21
at /scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:271:33
at /scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:778:35
at Cursor.close (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:1009:5)
at Cursor.nextObject (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:778:17)
at Cursor.each (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:264:12)
The action that I have written is
seneca.add("role:diff,cmd:getparams", function(msg, respond) {
seneca.ready(function() {
var collection = seneca.make$("paramStore");
var f = msg.payload;
seneca.log.info("Filter", f);
collection.list$(f, function(err, ob) {
if (err) {
seneca.log.error(err);
respond(err);
} else {
seneca.log.info("Result", ob);
respond(null, ob);
}
});
});
});
The same piece of code was working and now I am getting this error. Not sure what changed. Any help/suggestions are greatly appreciated.
The issue I was facing was because of this bit of code in the module's js file
if( _.isObject( result.out ) ) {
_.each(result.out,function(v,k){
if(~k.indexOf('$') && 'http$' !== k) {
delete result.out[k]
}
})
The _.each function is meant to parse a JSON object, where in my case the out was actually a JSON array. Wrapping the array into an object resolved it.

Meteor delay find() so that I can access the object

I've got a findOne() in a template helper in Meteor but I want to modify an array in the document before returning both the document as well as the updated array. When doing so I get TypeError: Cannot read property 'access' of undefined. On the initial test it worked fine but I suspect that it's now failing because I'm trying to modify the document before findOne() completes. How do I get around this? Code below:
'curMatter': function() {
var curObj = Matters.findOne({_id:Session.get('editing_matter')});
var curAccess = _.without(curObj.access, Meteor.userId());
return { curMatter: curMatter, curAccess: curAccess };
}
Collection.findOne completes before running code code that is after it (var curAccess = _.without(curObj.access, Meteor.userId()); in your case).
The issue is that the document that you expect to get by this query is not available (yet) to the client, so Matters.findOne({_id:Session.get('editing_matter')}); returns undefined.
So what it really means that your subscription is not ready, when the helper is run for the first time, and it fails.
What you can do is to check whether curObj is not undefined before accessing its property (i.e. var curAccess = curObj && _.without(curObj.access, Meteor.userId());
When the document becomes available to the client, the helper will be re-run, and you will get correct results then.
Here is your complete code:
'curMatter': function() {
var curObj = Matters.findOne({_id:Session.get('editing_matter')});
var curAccess = curObj && _.without(curObj.access, Meteor.userId());
return { curMatter: curMatter, curAccess: curAccess };
}
just use it as a cursor, they always seem to work better anyway.
Template['someTemplate'].helpers({
curMatter: function () {
return Matters.find({
_id: Session.get('editing_matter')
}).map(doc => Object.assign(doc, {
curAccess: _.without(doc.access, Meteor.userId())
}))
}
});
Then you can use an {{#each}} in your template (even if it is always one item)

Using Restangular, can I use a jsonResultsAdapterProvider when needing to override the id field?

I've got a mySql db with non-standard IDs and field names, so I was trying to use both jsonResultsAdapterProvider and setRestangularFields. Here's the code in my app.config file:
RestangularProvider.setBaseUrl(remoteServiceName);
RestangularProvider.setRestangularFields({id: 'personID'});
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
if (data.error) {
return data.error;
}
var extractedData = data.result;
return jsonResultsAdapterProvider.$get().camelizeKeys(extractedData);
});
RestangularProvider.addRequestInterceptor(function(elem, operation, what, url) {
return jsonResultsAdapterProvider.$get().decamelizeKeys(elem);
});
It's all good until I try to do a put/save. When I look at the request payload within the browser dev tools, it's: {"undefined":12842} (but the url is correct, so I know the id is set) If I don't use the ResultsAdapter and change the id field to Person_ID, payload looks good, so I know I'm making the right calls to Get and Save the Restangular objects. But for what it's worth, here's the code:
$scope.tests = Restangular.all('members').getList().$object;
vm.testEdit = function () {
$scope.test = Restangular.one('members', 12842).get().then(function(test) {
var copy = Restangular.copy(test);
copy.title = 'xxxx';
copy.put(); // payload was: undefined: 12842
});
}
// I also tried customPUT...
// copy.customPUT(copy, '', {}, {'Content-Type':'application/x-www-form-urlencoded'});
I tried "fixing" the id other ways too, too. like this:
Restangular.extendModel('members', function(model) {
model.id = model.personID;
return model;
});
but that messed up the urls, causing missing ids. And I tried getIdFromElem, but it only got called for my objects created with Restangular.one(), not with Restangular.all()
Restangular.configuration.getIdFromElem = function(elem) {
console.log('custom getIdFromElem called');
if (elem.route === 'members') { // this was never true
return elem[personID];
}
};
It seems like Restangular needs to substitute 'personID' most of the time, but maybe it needs 'Person_ID' at some point during the Save? Any ideas on what I could try to get the Save working?
I finally figured it out! The problem was in my config code and in the way I was decamelizing. Because of inconsistencies in my db field names (most use underscores, but some are already camelCase), I was storing the server's original elem names in an array within the jsonResultsAdapterProvider. But since I was calling jsonResultsAdapterProvider.$get().camelizeKeys(extractedData); within the interceptors, I was reinstantiating the array each time I made a new request. So, the undefined in the PUT request was coming from my decamelizeKeys() method.
My updated config code fixed the problem:
RestangularProvider.setBaseUrl(remoteServiceName);
RestangularProvider.setRestangularFields({id: 'personID'});
var jsonAdapter = jsonResultsAdapterProvider.$get();
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
if (data.error) {
return data.error;
}
var extractedData = data.result;
// return extractedData;
return jsonAdapter.camelizeKeys(extractedData);
});
RestangularProvider.addRequestInterceptor(function(elem, operation, what, url) {
return jsonAdapter.decamelizeKeys(elem);
});