Node-Postgres Module
1
1
1
Database integration with Node-Postgres.
A PostgreSQL server can handle a limited number of NodeJs client connections. The initial connection "handshake" data exchange can slow down the application.
The node-postgres (pg) library offers connection pooling through its pg-pool module. This module creates a pool of reusable connections for database query requests.
We create a new Pool instance with the credentials to connect to the database, we add SQL queries to the Node endpoints and res.rows as an array of objects.
const { Pool } = require('pg');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'postgres',
password: 'mrlzarate',
port: 5432
});
app.get("/hotels", function(req, res) {
pool.query('SELECT * FROM hotels', (error, result) => {
res.json(result.rows);
});
});

To implement CRUD operations in a pool.query() we use then() and catch().
//We added an alternative pool.query() on endpoint route query
//We separate the query declaration form its if statement value
http://localhost:3020/fila/?name=dodici
app.get("/fila", (req, res)=>{
let nomefila = req.query.name
let query;
if( nomefila ){
query = `select * from tavola where nome like '%${nomefila}%' order by id;`
}
pool
.query(query)
.then((result)=>{res.send(result.rows)})
.catch((error)=>{res.send(error)})
})
A single endpoint can chain multiple SQL queries.
We put them one after the other (the result.rows will be from the last SQL query).
Promise chaining manages asynchronous database queries. The .then() callback executes upon successful queries, granting access to the returned result. The .catch() handler manages errors from each query in the chain.
//"http://localhost:3020/remova/223"
//The first then(result) will return the rowCount of the delete
app.get("/remova/:index", (req, res)=>{
let index = Number( req.params.index )
pool.query(`delete from multi where age= ${index}`)
.then(result => { //returning * will retun the deleted row
return pool.query(`select * from multi`); //Select after delete on table
})
.then(result => {
res.json(result.rows); //returns remaining rows.
})
.catch(error => {
res.status(500).json({ error: 'Database error' });
})
We validate the client's req.body data by res.status(400).
//If the req.body data is invalid we return an error status 400
if (
!Number.isInteger(anni) || anni <= 0 ||
typeof anni === "string" || typeof comple !== "string"
){
return res
.status(400)
.send("The number of rooms should be a positive integer.");
}
To Select Join reference tables we need additional conditions.
//we need the 2 int properties to be equal AND the referenced id params.value
app.get("/sopra/:num", (req, res)=>{
let num = Number( req.params.num );
let query = 'select * from sopra inner join tavola on tavola.id=sopra.persona
and sopra.persona = $1'
pool
.query(query, [num])
.then((result)=>{ res.send( result.rows )})
.catch((error)=>{ res.send(error) } )
})

1
Last updated
Was this helpful?