Skip to content

Commit

Permalink
Merge pull request #29 from Memmo-App/master
Browse files Browse the repository at this point in the history
Fix leaking transaction, favor transaction from context over creating new one
  • Loading branch information
joaonice authored May 26, 2021
2 parents 1066455 + 33e18c3 commit f7120cb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ module.exports = options => {

getQuery(update, queryOptions, context) {
return options.fields.reduce((queries, field, index) => {
const knex = Model.knex() || context.transaction;
const knex = context.transaction || Model.knex();
const collection = knex(this.constructor.tableName);
const fields = castArray(field);

Expand Down
17 changes: 16 additions & 1 deletion test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ describe('FoobarController', () => {

it('should throw an error if there is no fields or identifiers options.', () => {
try {
const TestModel = modelFactory();
modelFactory();

fail();
} catch (e) {
Expand Down Expand Up @@ -88,6 +88,21 @@ describe('FoobarController', () => {

expect(result).toEqual({ bar: 'bar', biz: null, foo: null, id: 1 });
});

it('should favor transaction from context', async () => {
const TestModel = modelFactory({
fields: [['bar', 'foo']]
});

const result = await TestModel.knex().transaction(async trx => {
const { id } = await TestModel.query(trx).insert({ bar: 'bar', biz: 'biz', foo: 'foo' });
const result = await TestModel.query(trx).findById(id);

return result;
});

expect(result).toEqual({ bar: 'bar', biz: 'biz', foo: 'foo', id: 1 });
});
});

describe('$beforeUpdate', () => {
Expand Down

0 comments on commit f7120cb

Please sign in to comment.