Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
How to do some constraint checking during knex/objectionjs raw query

I am doing some raw query binding in objectionjs and my code is as follows:

const item = await cart.$relatedQuery('items').insert(req.body)
            .onConflict(['cartId', 'productId'])
            .merge({
                amount: raw('cart_item.amount + ?', req.body.amount),
                price: raw('cart_item.price + ?', req.body.price)
            });

Values for req.body.amount and req.body.price can be both positive and negative. Because of this, at some point the final value for amount and price fields in the database might become negative too after the addition/subtraction. And I want to prevent that from happening. What should I do in such case?

I tried the following:

amount: Math.max(raw('cart_item.amount + ?', req.body.amount), 0)

But this doesn't work (of course it shouldn't) and returns NaN. I don't want to put an .unsigned() check on the field itself, but check during runtime. Is there any way I can get what I want without making multiple queries to fetch the values for amount and price beforehand and checking before inserting the new values?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Can you do this?

amount: raw('cart_item.amount + ?', ((cart_item.amount + req.body.amount) >= 0) ? req.body.amount : 0 ),
about 4 years ago · Juan Pablo Isaza Denunciar

0

the way i would do it at runtime is using transactions:

const trx = await Item.startTransaction()

try {
    const item = await cart
        .$relatedQuery('items', trx) // make sure to pass the transaction
        .insert(req.body)
        .onConflict(['cartId', 'productId'])
        .merge({
            amount: raw('cart_item.amount + ?', req.body.amount),
            price: raw('cart_item.price + ?', req.body.price)
        });

    if (item.price < 0 || item.amount < 0 ) {
        // this will trigger the catch block and revert the operation
        throw new Error(...)
    }
    // success return as response or something
    res.json(item)

    await trx.commit()
} catch (err) {
    await trx.rollback()
    return next(err)
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda