能够使用反对 ORM 在 feathersjs 中实现事务。
结果如下。
交易挂钩
const {transaction} = require('objection');
// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
// eslint-disable-next-line no-unused-vars
const start = (options = {}) => {
return async context => {
const { service } = context;
const Model = service.Model;
const trx = await transaction.start(Model); // use Model if you have installed a knex instance globally using the Model.knex() method, otherwise use Model.knex()
context.params.transaction = { trx };
return context;
};
};
const commit = (options = {}) => {
return async context => {
const { transaction } = context.params;
await transaction.trx.commit();
return context;
};
};
const rollback = (options = {}) => {
return async context => {
const { transaction } = context.params;
await transaction.trx.rollback();
};
};
module.exports = {
_transaction: {
start,
commit,
rollback
}
};
然后在您的service.hooks中使用以下内容:
const {_transaction} = require('../../hooks/transaction-hooks');
module.exports = {
before: {
all: [],
find: [],
get: [],
create: [_transaction.start(),createRideData],
update: [],
patch: [],
remove: []
},
after: {
all: [],
find: [],
get: [],
create: [updateRideRequestStatus, _transaction.commit()],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [_transaction.rollback()],
update: [],
patch: [],
remove: []
}
};
也可以使用 knex 实例启动事务:
const start = (options = {}) => {
return async context => {
const { service, app } = context;
const knex = app.get('knex');
const trx = await transaction.start(knex);
context.params = {
...context.params,
transaction: {
trx
}
}
return context;
};
};