fix: añadida transacción

This commit is contained in:
Vicent Llopis 2022-11-25 11:50:24 +01:00
parent e540bf7b31
commit bd91d4a649
2 changed files with 42 additions and 12 deletions

View File

@ -26,11 +26,30 @@ module.exports = Self => {
Self.setSaleQuantity = async(saleId, quantity) => {
const models = Self.app.models;
const myOptions = {};
let tx;
const sale = await models.Sale.findById(saleId);
return await sale.updateAttributes({
originalQuantity: sale.quantity,
quantity: quantity
});
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const sale = await models.Sale.findById(saleId, null, myOptions);
const saleUpdated = await sale.updateAttributes({
originalQuantity: sale.quantity,
quantity: quantity
}, myOptions);
if (tx) await tx.commit();
return saleUpdated;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};

View File

@ -2,15 +2,26 @@ const models = require('vn-loopback/server/server').models;
describe('setSaleQuantity()', () => {
it('should change quantity sale', async() => {
const saleId = 30;
const newQuantity = 10;
const tx = await models.Ticket.beginTransaction({});
const originalSale = await models.Sale.findById(saleId);
try {
const options = {transaction: tx};
await models.Collection.setSaleQuantity(saleId, newQuantity);
const updateSale = await models.Sale.findById(saleId);
const saleId = 30;
const newQuantity = 10;
expect(updateSale.originalQuantity).toEqual(originalSale.quantity);
expect(updateSale.quantity).toEqual(newQuantity);
const originalSale = await models.Sale.findById(saleId, null, options);
await models.Collection.setSaleQuantity(saleId, newQuantity, options);
const updateSale = await models.Sale.findById(saleId, null, options);
expect(updateSale.originalQuantity).toEqual(originalSale.quantity);
expect(updateSale.quantity).toEqual(newQuantity);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});