Hi i am new to strongloop i want to know can i write my app logic inside a custom model. Like in example below i am getting data from orders table and on success i want to use its response in my logic.
Orders.createOrder = function(cb) {
Orders.findById( userId, function (err, instance) {
response = "Name of coffee shop is " + instance.name;
cb(null, response);
/***** want to write my logic here *****/
console.log(response);
});
cb(null, response);
};
Orders.remoteMethod(
'createOrder',
{
http: {path: '/createOrder', verb: 'get'},
returns: {arg: 'status', type: 'string'}
}
);
so is it the write place to do it or i have to write it somewhere else?
Your code has several issues, but the answer is pretty much yes.
You should call the callback function cb
when your application logic is done, and not before. Also, you should pay attention to feed any errors to the cb
, otherwise you're in for some big debugging headaches down the road.
Also, you need to pay extra attention to the way you're calling callbacks. In your current code, cb
will be called twice for any request, at the very end of createOrder
and in findById
. This is not good, because for one request you tell the server you have completed two. Also, the callback at the end of createOrder
is called immediately, before findById
is complete.
So corrected code would look like this
Orders.createOrder = function(cb) {
Orders.findById( userId, function (err, instance) {
// Don't forget stop execution and feed errors to callback if needed
// (other option : if errors are part of normal flow, process them and continue of course)
if (err) return cb(err);
response = "Name of coffee shop is " + instance.name;
console.log(response);
// Application logic goes there
// Complete the remote method
cb(null, response);
});
// No calls here to the callback
};
Orders.remoteMethod(
'createOrder',
{
http: {path: '/createOrder', verb: 'get'},
returns: {arg: 'status', type: 'string'}
}
);