How to use Sequelize Transaction inside a node-schedule job?

37 views Asked by At

How do I use Sequelize Transaction insde a node-schedule job?

For example I have this function here:

    async doSomething(
        params
    ) {

        // Create > Transaction1
        const transaction1 = await sequelize.transaction();

        try {
        
            await this._conversation.update(
                {
                    status: 'something'
                }, {
                    where: {
                        id: conversation.id
                    },
                    transaction: transaction1,
                })
                .then(data => {
    
                    // Do Nothing
    
                })
                .catch(err => {
    
                    // Throw > Error
    
                });
        

            /*
            |--------------------------------------------------------------------------
            | Schedule > Job
            |--------------------------------------------------------------------------
            */
            
            schedule_date = "some schedule date"
            
            const job = schedule.scheduleJob(
                "campaign_" + campaign.id, // Job ID
                schedule_date, // Schedule Date
                async function(){

                    // Create > Transaction2
                    const transaction2 = await sequelize.transaction();

                    try {

                        let create_result = await this._campaign.create(data, {
                            transaction: transaction2
                        })
                            .then(data => {
    
                                // Do Nothing
    
                            })
                            .catch((err) => {
    
                                // Throw > Error
    
                            });
                            
                        await transaction2.commit();

                    }
                    catch (err)
                    {
            
                        // DB > Rollback
                        await transaction2.rollback();
            
                    }  

                }, () => {

                });
                    
            await transaction1.commit(); 
            
        }
        catch (err)
        {

            // DB > Rollback
            await transaction1.rollback();

            // Throw > Error Object
            throw err

        }        
                        
    }

You can see in the function, I have a sequelize update() using transaction1 and sequelize create() inside the node-schedule job using transaction2

Is this correct?

0

There are 0 answers