Sequelize-typescript: How to use transaction with async/await?

Created on 20 Mar 2018  路  2Comments  路  Source: RobinBuschmann/sequelize-typescript

Hi,

I am facing an issue related to transaction, my code as below

import * as clsHooked from 'cls-hooked';
// import * as cls from 'continuation-local-storage';
import * as clsBluebird from 'cls-bluebird';
import { Sequelize, ISequelizeConfig } from 'sequelize-typescript';
import * as bluebird from 'bluebird';

const ns = clsHooked.createNamespace('sequelize-transaction-namespace');

clsBluebird(ns, bluebird);
Sequelize.useCLS(ns);

Then when I trying to execute create entity within transaction, but rollback does not work

return this.sequelize.transaction(async (trx) => {
            await Permit.upsert({
                companyId: 1,
                userId: 1
            });

            throw new Error('Should be rollback');
        });

To make this works, I have to pass the trx manually

return this.sequelize.transaction(async (trx) => {
            await Permit.upsert({
                companyId: 1,
                userId: 1
            }, { transaction: trx });

            throw new Error('Should be rollback');
        });

Do we have any solution or workaround to fix this issue?

Most helpful comment

@RobinBuschmann Rob actually, I got it working using below code

import { createNamespace } from "cls-hooked"
import { Sequelize } from "sequelize-typescript"
const namespace = createNamespace("sequelize-cls-namespace")

(Sequelize as any).__proto__.useCLS(namespace)

As you can see, we need to assign the namespace to the original Sequelize object, not the one sequelize-typescript returns.

All 2 comments

Hey @stormit-vn according to the sequelize docs (http://docs.sequelizejs.com/manual/tutorial/transactions.html) there is no other way than passing them manually to get the transactions to work. Or have I overseen something?

@RobinBuschmann Rob actually, I got it working using below code

import { createNamespace } from "cls-hooked"
import { Sequelize } from "sequelize-typescript"
const namespace = createNamespace("sequelize-cls-namespace")

(Sequelize as any).__proto__.useCLS(namespace)

As you can see, we need to assign the namespace to the original Sequelize object, not the one sequelize-typescript returns.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bschveitzer picture bschveitzer  路  5Comments

fareshan picture fareshan  路  3Comments

thestrayed picture thestrayed  路  5Comments

nandox5 picture nandox5  路  3Comments

lilling picture lilling  路  4Comments