javascript - 使用 Objection ORM 在 feathersjs 中进行事务
问题描述
feathers -objection - Objection.js的服务适配器- 构建在 Knex 之上的最小 SQL ORM。
事务是关系数据库中的原子和孤立的工作单元。
我们想在使用 Feathers CLI 生成的 feathersjs 应用程序中创建和使用事务。
但
我们无法弄清楚如何使用事务参数运算符创建事务对象并将其传递给一系列服务调用,以及如何使用 await transaction.trx.commit()和 await transaction.trx.rollback()。
同样需要帮助。
解决方案
能够使用反对 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;
};
};
推荐阅读
- excel - 如果只有 1 个 if 和 1 个 end if,如何解决“如果没有阻塞则结束”?
- java - 在哪里可以找到使用 java 的 ax 指南?
- vue.js - 如何在我的 v-data-table Vuetify Vuex Axios API 中添加 API
- python - 在 AWS 中运行 python 脚本的最佳方式是什么?
- azure - 如何检查 Azure 应用程序网关的当前实例数
- java - 如何获取 POI API 的依赖关系?
- reactjs - 强制焦点到在上一次渲染中禁用的按钮元素
- c# - 使用可变键反序列化 JSON
- php - 如何使用搜索词修复查询返回大量数据
- reactjs - 如何重定向 HashRouter URL 以使用 BrowserRouter