0
votes

I am seeing an odd behaviour in my Loopback app. I will try to describe it below.

I have a BaseModel which all my models inherit from that has operation hooks on 'access' and 'beforeSave' to populate a column for multitenancy reasons. It needs access to the current user and I'm fetching it as follows:

var httpContext = require('loopback').getCurrentContext();
var accessToken = httpContext.get('accessToken');
const userId = accessToken && accessToken.userId;

Then, one of my models needs to insert records in a second model. Model1 and Model2 have a one to one relationship. I have added a remote method for it and I'm doing it in a transaction as follows:

Model1.beginTransaction({ isolationLevel: Model1.Transaction.READ_COMMITTED })
.then(function(tx) {
    transaction = tx;
    return Model1.create({ paramId: param }, { transaction: transaction });
})
.then(function(model1) {
    return Model2.create({ model1: model1 }, { transaction: transaction });
})
.then(function(model2) {
    model2Instance = model2;
    return transaction.commit();
})
.then(function() {
    cb(null, model2Instance);
})
.catch(function(err) {
    if (transaction) {
        transaction.rollback(function(rbe) {
            cb(err, null);
        });
        return;
    }
    cb(err, null);
})

The hook fails when running the Model2.create step due to accessToken being undefined.

If I do remove { transaction: transaction } from my model calls both records are created successfully, though not using the database transaction as intended.

What am I missing?

1

1 Answers

0
votes

Have tried using transactions in loopback, but no success, due to incomplete or non descriptive documentation from the loopback side.

It is better to use http://knexjs.org/ for building the query and also for transactions.

Here is a reference link which states the same. How To Implement ACID Transactions in Loopback http://knexjs.org/#Transactions