I would like to create a module, where i have a function where i can insert a sql statement and get the result as recordset. Im new to nodeJs and have some trouble in accessing the functions right.
my Modul (sql.js)
var exports = module.exports = {};
sql = require('mssql');
let config = {
user: '###',
password '###'
server: '###',
database: '###',
driver: "###",
options: {
trustedConnection: true
}
};
var db = function (query) {
var rc;
console.log('verbinde');
sql.connect(config, function (err) {
console.log('verbinde');
if (err) console.log(err);
let request = new sql.request();
request.query(query, function (err, recordset) {
if (err) console.log(err);
console.log(recordset);
rc = recordset;
});
})
sql.close();
}
exports.db = db;
call
const ipc = require('electron').ipcMain;
const sql = require('../../customModules/sql.js');
console.log(sql.db('SELECT * FROM devices'));
i get an undefined.
it seems like, the sql.connect isnt rly called.
You might get better results using a Promise. Perhaps something like this (untested):
// sql.js
var db = (query) => new Promise((resolve, reject) => {
console.log('verbinde');
sql.connect(config, function (err) {
console.log('verbinde');
if (err) reject(err);
let request = new sql.request();
request.query(query, function (err, recordset) {
if (err) reject(err);
console.log('got those records!');
resolve(recordset);
});
})
sql.close();
})
// call
const ipc = require('electron').ipcMain;
const sql = require('../../customModules/sql.js');
sql.db('SELECT * FROM devices')
.then(data => console.log(data))
.catch(e => console.log(e));
Related
I am using SAP HANA CLIENT for NodeJS in my AdonisJS project. I am unable to return the response as json from the the function that connects to the database. Here is the code
The controller method validateInvoice is first called
async validateInvoice({request, response}) {
const req = request.all()
const inv_num = req.invoice_num;
const data = await this.fetchInvStatus(inv_num);
return response.json({success: true, data: data});
}
This in turn calls the fetchInvStatus method which actually connects to HANA DB
var conn = hana.createConnection();
var conn_params = {
serverNode: '127.0.0.1:30015',
uid: 'CUST_USER_ROLE_ADMIN',
pwd: 'Welcome#1234',
database: 'DED'
};
conn.connect(conn_params, (err) => {
if(err) {
return err;
}
conn.exec("Select * FROM SAPDED.YACSF_RRHD where INVOICE_NUMBER = ?", ['BOMT000005'], (err, result) => {
if (err) {
return err;
}
console.log(result);
return result;
})
});
In the console I'm able to see the result but this result is not being passed to the validateInvoice method so that the API could return the response.
The line in the first method response.json() is executed even before the data from DB is returned. How can I overcome this problem? I've tried adding return statement to conn.connect and conn.exec but nothing helps!
You have to return promise in the fetchInvStatus method.
function fetchInvStatus() {
return new Promise(resolve, reject) {
var conn = hana.createConnection();
var conn_params = {
serverNode: '127.0.0.1:30015',
uid: 'CUST_USER_ROLE_ADMIN',
pwd: 'Welcome#1234',
database: 'DED'
};
conn.connect(conn_params, (err) => {
if(err) {
reject(err);
}
conn.exec("Select * FROM SAPDED.YACSF_RRHD where INVOICE_NUMBER = ?", ['BOMT000005'], (err, result) => {
if (err) {
reject(err);
}
console.log(result);
resolve(result);
})
});
}
}
When i try to get result from node-postgres from my express app, pool.query is returning undefined result when i log it in console. Not sure if its about database connected properly or I am not returning the result properly? I am using heroku to deploy the app and using connection string given by heroku. Cant figure it out, anyone there to help please?.
db.js:
const { Pool } = require('pg');
const conString = process.env.DATABASE_URL;
const pool = new Pool({
connectionString: conString,
ssl: {rejectUnauthorized: false}
});
module.exports ={
getResult: (sql, params, callback)=>{
pool.query(sql, [params], (error, results)=>{
console.log(results);
if(!error){
callback(results);
}else{
callback(null);
}
pool.end();
});
}
}
user-model.js
var db = require('./db');
module.exports ={
findUserById: (userId)=>{
return new Promise((resolve, reject)=>{
var sql = "select id from users where id=?";
db.getResult(sql, [userId], (result)=>{
if(result.length>0){
resolve(true);
}else{
resolve(false);
}
});
});
}
}
seems the sent query parameter is in mysql format, use node-postgres format which is var sql = "select id from users where id = $1"; which should return valid result
It seems that your use of params is not correct.
You're passing an array to db.getResult(), then using it as the first element of another array.
Should just be pool.query(sql, params, (error, results)=>{ on that line.
you need to get the pool connection
const pool = require('./pool');
module.exports = {
// my version
findUserById(sql, params) {
return new Promise((resolve, reject) => {
return pool
.connect()
.then(conn => {
conn
.query(sql, [params])
.then(result => {
conn.release()
resolve(result)
})
.catch(error => {
conn.release()
reject(error)
})
})
})
},
// your version
findUserByIds: (userId) => {
return new Promise((resolve, reject) => {
var sql = "select id from users where id=?";
db.getResult(sql, [userId], (result) => {
if (result.length > 0) {
resolve(true);
} else {
resolve(false);
}
});
});
}
}
//// in you main or you controller file
// use the function
const { findUserById } = require('./model')
app.get('/user/:id', (req, res) => {
let sql = 'select * from "users" where "userId"= $1';
findUserById(sql, 1)
.then(result => {
res.status(200).send({
data: result
})
})
.catch(error => {
res.status(400).send(error)
})
})
I start to develop a simple web application with NodeJS. and when I try to get a list record from SQL Server to show on the list page but somehow it's not working.
Here is the code :
const express = require("express");
const bodyParser = require("body-parser");
const sql = require("mssql");
const DBUtils = require("./DBUtils");
const app = express();
app.get("/all", (req, res, next) => {
let mypromise = new Promise((reso, rej) => {
let nameList = DBUtils.getNameList(sql);
if (nameList !== null || typeof nameList !== "undefined") {
reso(nameList);
} else {
rej("Error");
}
})
.then((result) => {
res.send(result);
})
.catch((err) => {
console.log(err);
});
});
app.get("/", (req, res, next) => {
console.log("the / route");
res.send("<h1>Hello to NodeJS</h1>");
});
app.listen(5003);
My DBUtils
const config = {
user: "sa",
password: "123",
server: "DESKTOP-7KGJI7L", // You can use 'localhost\\instance' to connect to named instance
database: "java",
options: {
encrypt: false,
},
};
const getNameList = (sql) => {
let nameList = "";
let errorString = "";
// Create connection
sql.connect(config, function (err) {
// Err
if (err) {
console.log(err);
}
// Create Request object
let sqlRequest = new sql.Request();
// QueryString
let queryString = `select * from NAME`;
// Run the query
sqlRequest.query(queryString, (err, data) => {
if (err) console.log(err);
//console.log(data); //data.recordset(array)[index].name
data.recordset.forEach((el) => {
nameList += `<li>${el.name}</li>`;
});
return nameList;
});
});
};
exports.getNameList = getNameList;
I pretty sure something wrong in Promise line but don't know how to fix it. Any suggest?
I think you are a newbie in Nodejs You made a common mistake. You did not use promise pattern correctly. Also, no need to pass next callback unless required.
Change getNameList as below :
const getNameList = (sql) => {
let nameList = "";
let errorString = "";
// Create connection
return new Promise (function(resolve,reject) {
sql.connect(config, function (err) {
// Err
if (err) {
console.log(err);
reject(err)
}
// Create Request object
let sqlRequest = new sql.Request();
// QueryString
let queryString = `select * from NAME`;
// Run the query
sqlRequest.query(queryString, (err, data) => {
if (err) {console.log(err)
reject(err)
}
//console.log(data); //data.recordset(array)[index].name
data.recordset.forEach((el) => {
nameList += `<li>${el.name}</li>`;
});
resolve(nameList);
});
});
})
};
Change app.get("/all") as below:
app.get("/all", (req, res) => {
DBUtils.getNameList(sql).then(function(list) {
res.status(200).send(list)
}).catch(function(err) { //handle error here
res.status(500)
})
})
Moreover, learn how to use promises and async-await.
Use appropriate body-parser as per requirement ie json, text etc.
Learn how and when to use next
Want to connect two different database engines (i.e Postgres and Mssql) using nodeJS in lambda script.
exports.handler = (event, context, callback) => {
try {
sql.connect(config, (err) => {
if (err) {
console.log(err);
callback(err);
} else {
const req = new sql.Request();
req.query("select top 10 * from queue", async (error, result) => {
if (error) {
console.log(error);
callback(error);
} else {
const { Client } = require('pg');
const client = new Client();
await client.connect();
var res = await client.query("select * from nq");
var notificationData = res.rows;
console.log(notificationData);
console.log(params);*/
sql.close();
callback(null, result.recordset);
}
});
}
});
sql.on('error', (err) => {
console.log(err);
callback(err);
});
} catch (e) {
console.log(e);
console.error(e);
sql.close();
}
};
Want to retrieve data from SQL server database and based on the ID want to retrieve similar data from Postgres Database from the same lambda script function.
I have a function connect to amazon RDS and select data from a table, but my callback function always return result is undefined. I used async/await for this function but it does't work.
My problem: I need function getOrder must be finished and return a result, after that call to callback.
My function:
'use strict';
let mysql = require('mysql');
let config = require('./config');
let pool = mysql.createPool({
connectionLimit : 10,
host : config.host,
user : config.user,
password : config.password,
database : config.database
});
exports.handler = async (event, context, callback) => {
let result = {};
try{
let sql = "SELECT * FROM tbl_test WHERE deleted = ? ";
result = await getOrder(sql,0);
}catch (err){
throw new Error(err);
}
console.log("-----Result: ",result);
return callback(null, {body: JSON.stringify(result),statusCode:200});
};
let getOrder = async (sql, params) => {
pool.getConnection((err, connection) => {
connection.query(sql, params, (err, results) => {
if (err){
throw new Error(err);
}
console.log("-----Query Done!");
connection.release();
console.log("-----Data: ", results);
return results;
});
});
};
Result when run:
result of function
To get it works, in your getOrder async function you should return a promise.
Ex:
let getOrder = async (sql, params) => {
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
connection.query(sql, params, (err, results) => {
if (err){
reject(err);
}
console.log("-----Query Done!");
connection.release();
console.log("-----Data: ", results);
resolve(results);
});
});
});
};