vitaly-t/pg-promise-demo

can't use "this" in transactions in product

Firlfire opened this issue · 1 comments

Hi,

I try transaction with your demo.
I added a GET which must first insert a User then a Product (if error during one, cancel all)

Maybe I'm wrong and just do not use the transactions correctly: is it possible to use 'this.add' instead of 't.products.add'? Because it's in repo products. Or is it this story of "context" specified in the doc?

// ./index.js
GET('/products/addNew/:userName/:productName', req => db.products.txTest(req.params));

the called method :

// ./db/repos/products.js
    txTest(values) {
        return this.db.tx('add-fullProduct', async (t)=> {
            const user = await t.users.add(values.userName);

            //return this.add({ userId: user.id, name: values.productName }); // ERROR : Key (user_id)=(17) is not present in table \"users\"."
            return await t.products.add({ userId: user.id, name: values.productName }); // works
        })
        .then(data => {
            data.done = true; // for example
            return data;
        })
        .catch(ex => {
            console.log(ex.message);
            return ex;
        });
    }

Sorry for opened this post,
I think that because transactions manage their connexion it's better to use t.users.add instead of this.add