在自定义模型 strongloop 中编写应用程序逻辑
Writing app logic in custom model strongloop
嗨,我是 strongloop 的新手,我想知道我能否在自定义模型中编写我的应用程序逻辑。就像下面的例子一样,我从订单 table 获取数据,成功后我想在我的逻辑中使用它的响应。
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'}
}
);
那么它是写的地方还是我必须写在别的地方?
您的代码有几个问题,但答案是肯定的。
您应该在应用程序逻辑完成时调用回调函数 cb
,而不是之前。此外,您应该注意向 cb
提供任何错误,否则您将在调试过程中遇到一些令人头疼的问题。
此外,您需要特别注意调用回调的方式。在您当前的代码中,cb
将针对任何请求调用两次,在 createOrder
的最后和 findById
中。这不好,因为对于一个请求,您告诉服务器您已经完成了两个请求。此外,createOrder
末尾的回调会在 findById
完成之前立即调用。
所以更正后的代码看起来像这样
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'}
}
);
嗨,我是 strongloop 的新手,我想知道我能否在自定义模型中编写我的应用程序逻辑。就像下面的例子一样,我从订单 table 获取数据,成功后我想在我的逻辑中使用它的响应。
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'}
}
);
那么它是写的地方还是我必须写在别的地方?
您的代码有几个问题,但答案是肯定的。
您应该在应用程序逻辑完成时调用回调函数 cb
,而不是之前。此外,您应该注意向 cb
提供任何错误,否则您将在调试过程中遇到一些令人头疼的问题。
此外,您需要特别注意调用回调的方式。在您当前的代码中,cb
将针对任何请求调用两次,在 createOrder
的最后和 findById
中。这不好,因为对于一个请求,您告诉服务器您已经完成了两个请求。此外,createOrder
末尾的回调会在 findById
完成之前立即调用。
所以更正后的代码看起来像这样
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'}
}
);