Feathersjs中使用异议ORM的交易

问题描述 投票:0回答:2

[feathers-objection-用于Objection.js的服务适配器-在Knex之上构建的最小SQL ORM。

事务是关系数据库中的原子工作和隔离的工作单元。

我们想在使用Feathers CLI生成的feathersjs应用程序中创建和使用事务。

但是

我们无法确定如何使用事务参数运算符创建事务对象并将其传递给一系列服务调用,以及如何使用await transaction.trx.commit()和await transaction。 trx.rollback()

同样需要帮助。

feathersjs objection.js feathers-service
2个回答
0
投票

knex.transcationProvider()检查https://knexjs.org/#Transactions示例

但是,在调用await trx.commit()await trx.rollback()的部分中,文档中可能存在错误。

更安全的方法是只调用没有awaitawait trx.executionPromise的任何一个,以获取事务结果/如果回滚则出错。

knex中的事务文档当前非常混乱。


0
投票

能够使用异议ORM在feathersjs中实现事务。

发现如下。

transaction-hooks

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;
  };
};
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.