Juili Potdar
Juili Potdar

Reputation: 11

Postgres Express and Node JS API- Multiple queries in one API endpoint

I have a postgres database where I am inserting data in three database tables. As I want to insert this data into all three tables on just one button click I dont want three different API endpoints. As I am new to node js and postgres I am unable to put all three queries in one api endpoint. Till now I am stuck at this-

app.post("/input",async(req,res)=>{
    try{
        const {a,b,c,d,e,f,g,h,i}= req.body;
        const newentry=await pool.query(
            "INSERT INTO num(a,b,c) VALUES($1,$2,$3) RETURNING *",
            [a,b,c],
            'INSERT INTO order(d,e,f) VALUES ($1,$2,$3) RETURNING *' ,
            [d,e,f],
            'INSERT INTO quantity(g,h,i) VALUES ($1,$2,$3) RETURNING *' ,
            [g,h,i]

            );

         
            res.json(newentry.rows[0]);
           

        
    } catch(err){
        console.error(err.message);
    }
});

Upvotes: 0

Views: 464

Answers (1)

GMB
GMB

Reputation: 222412

You seem to want common-table-expressions:

with 
    nums   as (insert into num (a, b, c)     values($1, $2, $3)),
    orders as (insert into "order" (d, e, f) values ($1, $2, $3)
insert into quantity (g, h, i) values ($1, $2, $3);

This allows running the three insert queries in a single statement.

returning does not really make sense here: which values would you like to return out of these three statements? Returning the values that were inserted is not a sensible approach: since you passed these values in the first place, you know the values already.

Upvotes: 1

Related Questions