Node/express postgresql stored procedure / function - node.js

I want to call a stored procedure / function in postgresql from node/express. I am using Angular 5.
Installed packages:
express: 4.16.2,
pg: ^7.4.0
Other required packages are also installed
Below is the code of my API - I want to replace all queries with my stored procedure / function call
const express = require('express');
const router=express.Router();
const {Pool,Client} = require('pg');
const connectionString = 'postgresql://postgres:1#localhost:5432/dbAngular'
// const client = new Client({
// connectionString:connectionString
// })
router.get('/employees', (err, res, done) => {
const client = new Pool({
connectionString:connectionString
})
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established message as follow '+err.message+'')
}
});
client.query('select * from getEmployees();', (err, result) => {
if (err) {
console.log(err.stack) ;
client.end();
} else {
client.end();
console.log(result.rows);
res.json(result.rows);
}
})
})
//SAVE
router.post('/employees', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
})
console.log( req.body);
var employee=req.body;
const query = {
text: 'INSERT INTO employes(name) VALUES($1)',
values: [employee.name]
}
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established '+err.message+'')
}
});
client.query(query, (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
})
});
//delete
router.delete('/employees/:id', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
});
console.log('id passed is ' + req.param.id);
client.query('DELETE FROM employes WHERE empid=($1)',[req.param.id], (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
});
});
module.exports=router;

Related

client.get("ping", (err, data) => in redis hangs my node js code

This is my server call to route
const redis = require("redis");
const client = redis.createClient();
client.connect();
module.exports = client;
This is my API route
app.get("/api/ping", middleWare.cacheRouteOne, RouteController.routeOne);
This is my cache route function
exports.cacheRouteOne = (req, res, next) => {
client.get("ping", (err, data) => {
console.log(data);//To check whether is working or not.
if (err) throw err;
if (data != null) {
res.json({
postss: JSON.parse(data),
});
} else {
next();
}
});
};
And this is my API call code
exports.routeOne = (req, res) => {
axios
.get("some APi CALL")
.then((response) => {
client.setEx("ping", 3600, JSON.stringify(response.data.posts));
console.log(client);
res.status(200).json({
status: true,
posts: response.data.posts,
});
});
};
When it calls the middle function it hangs my code after clinet.get()
I got the answer, I was making a call back but for forget to add await ,
so this is the updated middleware code
exports.cacheRouteOne = async (req, res, next) => {
let data = await client.get("ping");
console.log("data of ping");
if (data != null) {
res.json({
postss: JSON.parse(data),
});
console.log("yes");
} else {
next();
}
};
use this code to connect redis
const client = redis.createClient({
socket: {
port: 6379,
host: "127.0.0.1",
}
});
(async () => {
// Connect to redis server
await client.connect();
})();
console.log("Attempting to connect to redis");
client.on('connect', () => {
console.log('Connected!');
});
// Log any error that may occur to the console
client.on("error", (err) => {
console.log(`Error:${err}`);
});

Convert my existing Node Js code into Async Await

I am New To async/await coding in node js. I am trying to fetch data from mysql and then populate the result into an object. But i am not finding a way how to do it in controller.js file.
My source code similar to this.
My Router File
const express = require("express");
const controller = require("controller");
const router = express.Router();
router.route("/").get(controller.findAll);
My Controller File
const model = require("model");
exports.findAll = async (req, res) => {
const all = model.getAll((err, data) => {
if (err) {
res.status(500).send({
message: err.message || "Some error occurred while retrieving data.",
});
}
return data;
});
const user = model1.getUser((err, data) => {
if (err) {
res.status(500).send({
message: err.message || "Some error occurred while retrieving user.",
});
}
return data;
});
// somefunctionality(all, user);
// res.send(result);
};
My Model file
const con = require("./db");
// constructor
const Customers= function (customer) {
this.id = customer.id;
this.first_name = customer.first_name;
this.last_name = customer.last_name;
this.email = customer.email;
};
Customers.getAll = () => {
const query = `SELECT * FROM doctors`;
sql.query(query, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("customers: ", res);
result(null, res);
};
user model same as customer
Thanks for your help
The first thing I would do is covert your Customers.getAll method to return a promise:
model file
Customers.getAll = () => {
const query = `SELECT * FROM doctors`;
return new Promise((res, rej) => {
sql.query(query, (err, data) => {
if (err) {
console.log("error: ", err);
rej(err);
return;
}
console.log("customers: ", res);
res(data);
})
};
(Note that you'll probably have to do something similar to the getAll method for your User model)
Now, in the controller, you can use try/catch to handle any errors.
*controller file
exports.findAll = async (req, res) => {
try {
const all = await model.getAll();
const users = await model1.getUser();
const result = somefunctionality(all, user);
res.send(result);
} catch(err) {
res.status(500).send({
message: err.message || "Some error occurred while retrieving data.",
});
}
};

Local Host not succesful

Command Shot
Above I have a screen shot of my app.js server and for some reason the connection is not going through below I have my app.js code
const express = require('express');
const app = express();
const mysql = require('mysql');
const bodyparser = require('body-parser');
app.use(bodyparser.json());
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Adil#123',
database: 'movies'
});
mysqlConnection.connect(err=>{
if (err) {
console.log('It was not successful \n Error:' + JSON.stringify(err,undefined,2));
} else {
console.log('Its a success');
}
});
// Collecting all the movies from the movielist
app.get('/movielist',(req,res)=> {
mysqlConnection.query("SELECT * FROM movielist", (err, rows,fields)=> {
if (!err) {
res.send(rows);
} else {
console.log(err);
}
});
});
// Finding a movie based on the `idmovielist` number
app.get('/movielist',(req,res) => {
mysqlConnection.query("SELECT * FROM movielist WHERE idmovielist = ?",[req.params.id],(err, rows,fields) =>{
if (!err) {
res.send(rows);
} else {
console.log(err);
}
});
});
// Delting a movie
app.delete('/movielist/:id',(req,res) => {
mysqlConnection.query("DELETE FROM movielist WHERE idmovielist = ?",[req.params.id],(err,rows,fields) =>{
if (!err) {
res.send("Movie is deleted");
} else {
console.log(err);
}
});
});
// Inserting a movie
app.post('/movielist/addMovie',(req, res) => {
mysqlConnection.query("INSERT INTO movielist (`idmovielist`,`name`,`thumnail_path`,`description`,`language_released`,`year_released`) VALUES ('"+req.body.idmovielist+"', '"+req.body.name+"','"+req.body.thumnail_path+"', '"+req.body.description+"', '"+req.body.year_released+"', '"+req.body.language_released+"' )",
(err,rows) => {
if (!err) {
res.send("Movie is added");
} else {
console.log(err);
}
});
});
// Updating the movie list
app.put('/movielist/:id',(req,res) =>{
let update = req.body;
mysqlConnection.query("UPDATE movielist SET `year_released` WHERE = '"+update.idmovielist+"','"+update.year_released+"'",
(err, results) => {
if (!err) {
res.send("Movie list is updated");
} else {
console.log(err);
}
});
});
// localhost:3000
app.listen(3000,() => {
console.log('We got it running');
});
module.exports = app;
Above is my app.js the server was working earlier but for some reason it is not working anymore what can be the issue Is it something wrong with my code or should I change the port or create another server

Call sql functions in node.js modules using module.exports

I have my main routes file called main.js, in which I want to call sql functions from a module called database.js Within the database.js file I am able to retrieve the data, however when passing to main.js it keep saying that data is undefined.
main.js
const database = require('./modules/database')
app.get('/', async(req, res) => {
try {
const data = database.getAll()
console.log(data)
res.render('home', {stock: data})
} catch(err) {
console.log(err.message)
res.render('empty')
}
})
database.js
const sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database('./stockInventory.db', (err) => {
if (err) return console.error(err.message)
console.log('Connected to the "stockInventory.db" SQlite database.')
})
module.exports.getAll = () => {
const sql = 'SELECT * FROM stock;'
console.log(sql)
db.all(sql, (err, data) => {
if(err) console.error(err.message)
//console.log(data)
return data
})
}
You need callback function, Try this
const database = require('./modules/database')
app.get('/', async(req, res) => {
try {
database.getAll(function(data) {
console.log(data)
res.render('home', {stock: data})
})
} catch(err) {
console.log(err.message)
res.render('empty')
}
})
module.exports.getAll = (callback) => {
const sql = 'SELECT * FROM stock;'
console.log(sql)
db.all(sql, (err, data) => {
if(err) console.error(err.message)
//console.log(data)
callback(data);
})
}

Express: how to end response

I new in Nodejs and faced some problems and need help
I broke down my app into modules and controllers
in app.js
app.use('/api/sync', syncDataRouter)
and in syncDataRouter.js
const routes = function (con, Reading, ReadingSummary) {
const syncDataRouter = express.Router();
const syncDataController = require('../controller/syncDataController')(con, Reading, ReadingSummary);
//Get All Readings from Database and push it to Mongo-db
syncDataRouter.route('/')
.get(syncDataController.sync);
return syncDataRouter;
};
module.exports = routes;
and in controller
const syncDataController = function (con, Reading, ReadingSummary) {
function getAllCompletedSessions() {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM session WHERE endTime IS NOT NULL';
con.query(sql, (err, rows) => {
if (err) reject(new Error(err));
resolve(rows);
});
});
};
function getSessionPlayers(sessionId) {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM sessionplayers WHERE sessionId = ?';
con.query(sql, [sessionId], (err, rows) => {
if (err) reject(new Error(err));
resolve(rows);
});
});
};
const sync = (req, res) => {
getAllCompletedSessions()
.then(sessions => {
})
.catch(err => {
res.status(500).send({ message: err.message });
});
//The Problem
res.json('Done');
};
return {
sync: sync
}
}
module.exports = syncDataController;
the problem is if any error happened enter a catch block and also continue until res.json('Done'); and sent a message can't set headers after they are sent how to handle a situation like that
Try making the sql queries async
const syncDataController = function (con, Reading, ReadingSummary) {
async function getAllCompletedSessions() {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM session WHERE endTime IS NOT NULL';
await con.query(sql, (err, rows) => {
if (err) reject(new Error(err));
resolve(rows);
});
});
};
async function getSessionPlayers(sessionId) {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM sessionplayers WHERE sessionId = ?';
await con.query(sql, [sessionId], (err, rows) => {
if (err) reject(new Error(err));
resolve(rows);
});
});
};
const sync = (req, res) => {
getAllCompletedSessions()
.then(sessions => {
})
.catch(err => {
res.status(500).send({ message: err.message });
});
//The Problem
res.json('Done');
};
return {
sync: sync
}
}
module.exports = syncDataController;

Resources