我正在使用Sails.js v0.12.0
而我正在尝试修改policies
的链,以使用promises
(在我的情况下为bluebird
)。
如果在某些进行中的策略或操作中发生错误,则应该在promise catch
语句中捕获此错误,作为返回具有被拒绝状态的promise的嵌套函数的结果。
如果交易已经完成并且响应尚未发送到客户端,那么这也会冒泡。
在我的情况下,我想创建policy that creates database transactions
(isTransational.js
我使用MySQL数据库,Knex.js
用于此
并在继续应用逻辑中使用此transaction
。
为了更好地说明问题和我已经尝试过的事情:
isTransactional.js
/policies
文件夹中的Sails.js政策:
module.exports = function(req, res, next) {
// MAIN ISSUE: There I need to get reference to next middleware
// not fn(req, res, function (err) {...) like specified at
// sails/lib/router/bind.js:179. I tried to get it using
// `sails` event `route:route` but it does not fires at the
// right moment, trying to find other solution.
var PolicyNext = PolicyHelper.promisify(nextPolicy);
sails.knex.transaction(function(trx) {
// If somewhere in proceeding logic will be transaction
// commited, response to client can be handled inside,
// no need to bubble up to this level.
// If error occurs while performing transaction,
// first catch block will catch error, if no catch
// is present in whole chain, transaction error will be
// caught at this level.
PolicyNext(req, res);
}).then(function() {
sails.log.info('Transaction has been completed successfully.');
})
.catch(function(error) {
// If we get here, that means some part or transaction
// has failed.
sails.log.error(error);
});
};

PolicyHelper.promisify
sails.js
中间件功能转换为
承诺返回功能
promisify: function (policy) {
return new Promise(function (resolve, reject) {
var req = policy.req;
var res = policy.res;
policy.fn(req, res, function(err) {
// INVESTIGATE: (this would allow `req.params` aka route
// params to be changed in policies). Hold on to the current
// state of `req.params` after user code was run.
req._modifiedRouteParams = _.cloneDeep(req.params);
if (err) reject(err);
// Continue onwards
resolve();
});
});
},

有什么建议吗? 谢谢。