首页 > 解决方案 > 使用 Objection ORM 在 feathersjs 中进行事务

问题描述

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

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

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

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

同样需要帮助。

标签: javascriptfeathersjsobjection.jsfeathers-service

解决方案


能够使用反对 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;
  };
};

推荐阅读