'How to lock data during an update in objection.js

I am using objection.js with node. I am trying to use a custom validation function in the $beforeUpdate hook in my model and would like to know the best way to start a transaction so I can lock the records associated with the update.

What is the ideal way to do this?

This is my code so far

async $beforeUpdate (opt, queryContext) {
    const trx = await Assignment.startTransaction()
    await this.validateAssignmentOverlap(this, trx)
    queryContext._trx = trx
}

async $afterUpdate (opt, queryContext) {
    await super.$afterUpdate(opt, queryContext)
    await queryContext._trx.commit()
}

Here is my validation function:

async validateAssignmentOverlap (body, trx)
{
    try {
        Assignment.query(trx)
            .where('employee_id', '=', body.employee_id)
            .forUpdate()
       const data = await Assignment.query(trx)
            .where('employee_id', '=', body.employee_id)
            .whereRaw('(?, ?) OVERLAPS ("start_date", "end_date")',
                [body.start_date, body.end_date])
        if (data.length > 0) {
            throw new Error('Overlap Error')
        }
    } catch (e) {
        await trx.rollback()
        throw new Error(e)
    }
}

Thank you for the help



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source