How to get the mssql output in protractor + VSCode - node.js

I'm running the below code seems like the connection is made successfully but i do not see any output or is there any way to see the output of the query result, I'm new to this protractor nodeJS MSSQL connection.
const assert = require("../configuration.js");
const { config } = require("dotenv");
const { ConnectionPool } = require("mssql");
var sql = require('mssql');
config();
const c = {
driver: 'msnodesqlv8',
server: "server/nameORIP",
user: "UserName",
password: "Password",
database: 'DBname',
};
describe("mssql connection", () => {
it('test query', () => {
sql.connect(config, (err) => {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from NetUsers', (err, recordset) => {
if (err) console.log(err)
// send records as a response
request.send(recordset);
});
}); // end of sql.connect()
}) // end of it
})
Output
Request {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
canceled: false,
_paused: false,
parent: [Function: ConnectionPool],
parameters: {},
rowsAffected: 0 }

I didn't find any information for the method request.send(recordset); from their official documentation.
Supported methods in Request Object are:
execute - https://www.npmjs.com/package/mssql#execute
input - https://www.npmjs.com/package/mssql#input
output - https://www.npmjs.com/package/mssql#output
pipe - https://www.npmjs.com/package/mssql#pipe
query - https://www.npmjs.com/package/mssql#query
batch - https://www.npmjs.com/package/mssql#batch
bulk - https://www.npmjs.com/package/mssql#bulk
cancel - https://www.npmjs.com/package/mssql#cancel
request.query function will give you the list of records from the DB and pass it to the callback function and the values can be accessed directly using
request.query('select * from NetUsers', (err, resultArray) => {
if (err) console.log(err)
// if no error
console.log(resultArray.recordset[0]); //will print the first row from response.
});
Refer : https://www.npmjs.com/package/mssql#query-command-callback

I finally made it to work with few changes not only it connects but also runs the query and shows me the output in console, once again thank you for all the help.
import { async } from "q";
const sql = require('mssql/msnodesqlv8');
const assert = require("../configuration.js");
const poolPromise = new sql.ConnectionPool({
driver: 'msnodesqlv8',
server: "server/nameORIP",
user: "UserName",
password: "Password",
database: 'DBname',
})
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
;
describe('any test', () => {
it('verification', async () => {
try
{
const pool = await poolPromise;
const result = await pool.request()
.query('SELECT TOP (10) * FROM dbo.NetUsers')
console.log(result);
}
catch(err)
{
console.log(err);
}
});
});

Related

Node js + mysql2: Should I check for errors in both connection.on('error', fn1) and connection.connect(fn2), or one of these checks is sufficient?

My current code is:
const mysql = require('mysql2');
function createConnection() {
return new Promise((res, rej) => {
let connection = mysql.createConnection({
host: "127.0.0.1",
port: "3306",
user: "root",
database: "UniversityEmployeesDB",
password: ""
});
connection.on('error', function (err) {
console.log(`Error while creating a MySQL connection: ${err.toString()}`);
rej(err);
});
connection.connect(function (err) {
if (err) {
console.log(`Error while connecting to MySQL server: ${err.toString()}`);
rej(err);
}
else {
console.log("Connection with the MySQL server was successfully established.");
res(connection);
}
});
});
}
I tested it on error scenarios, turning off my local MySQL server and setting a wrong access login and/or password, and server console logs show that both onerror event and connection.connect fire on error showing exactly the same result. So I sespected that it would be reasonable to use only one of them, and using both could be redundant... But I still have doubts whether if I omit one, not all error types could be handled. Or is it really redundant?
I would suggest using a poolConnection over normal connections.
I am using a MVC based architecture with mysql2 and nodejs-express.
Here's how you can create the connector.js file for establishing database connections.
// connector.js
const mysql = require('mysql2');
var connection = mysql.createPool({
host: process.env.HOST,
// port: 3306,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 10,
multipleStatements: true
});
connection.getConnection((err) => {
if (err) console.log(JSON.stringify(err));
else {
console.log('Connected!')
}
});
module.exports = connection.promise();
And to execute a query use this method over con.query
const con = require('../database/connector.js');
const fn = async ( params ) => {
try{
const [data] = await con.execute('select * from tbl_users where user = ?',[params]);
return data;
} catch(err) {
return false;
}
}

AWS lambda api Postgres not won’t insert

I have the following AWS lambda handler:
exports.handler = async (event, data) => {
var AWS = require('aws-sdk/global');
const awsParamStore = require('aws-param-store');
const {
Pool
} = require('pg');
var host;
await awsParamStore.getParameter('testing-main-rds-url', { //get database host from AWS
region: 'us-east-1'
})
.then((parameter) => {
host = parameter.Value
});
var signer = await new AWS.RDS.Signer({
region: 'us-east-1',
username: 'developer',
hostname: host,
port: 5432
});
var token = await signer.getAuthToken({}); //get token from AWS
const db = await new Pool({
user: "developer",
host: host,
database: "main",
password: token,
port: 5432,
ssl: true,
});
const query = `INSERT INTO crm.user_crm
(u_id,username)
VALUES ($1,$2)`;
const values = [event.u_id, event.username];
db.connect((err, client, release) => {
if (err) {
throw("Error acquiring client.", err.stack);
} else {
client.query(query, values, (err, result) => {
release();
if (err) {
throw("Error executing query.", err.stack);
return ;
} else {
console.log("INSERT DONE");
db.end()
return {
statusCode: 200
};
}
})
}
})
};
This code will take in data and add it to a database.
When I run it on my computer with console.log(require('./index').handler(data)); it works perfectly and inserts the record. When I run it from lambda it returns nothing and doesn’t insert a record. Any help would be appreciated.
You mixing async/await with callback style. Your lambda function will finish before the query finish.
As example in pg document it supports async/await:
Instead of db.connect((err, client, release) => {...
const res = await pool.query(query, values);
console.log("INSERT DONE");
await pool.end()
return {
statusCode: 200
};

node-postgres returning undefined 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)
})
})

Azure functions integration with Postgres in Node.js

I want to access to Azure Postgres DB from an Azure function.
Below is the node.js source code of Azure function.
module.exports = async function (context, req) {
try {
context.log('Start function!');
var pg = require('pg');
const config = {
host: 'taxiexample.postgres.database.azure.com',
user: 'postgres#taxiexample',
password: 'QscBjk10;',
database: 'taxi',
port: 5432,
ssl: false
};
var client = new pg.Client(config);
const query = 'insert into taxi values (\'2\');';
context.log(query);
client.connect();
var res = client.query(query);
await client.end();
context.log(res);
} catch (e) {
context.log(e);
} finally {
context.res = {
status: 200,
body: "ok"
};
}
};
The record doesn't insert, the res object returns the following error:
2020-03-04T23:03:59.804 [Information] Promise {
<rejected> Error: Connection terminated
at Connection.<anonymous> (D:\home\site\wwwroot\HttpTrigger1\node_modules\pg\lib\client.js:254:9)
at Object.onceWrapper (events.js:312:28)
at Connection.emit (events.js:228:7)
at Socket.<anonymous> (D:\home\site\wwwroot\HttpTrigger1\node_modules\pg\lib\connection.js:78:10)
at Socket.emit (events.js:223:5)
at TCP.<anonymous> (net.js:664:12)
}
2020-03-04T23:03:59.811 [Information] Executed 'Functions.HttpTrigger1' (Succeeded, Id=944dfb12-095d-4a28-a41d-555474b2b0ee)
Can you help me? Thanks
I've resolve it, it was a trivial programming error.
Below is the correct source code
module.exports = async function (context, req) {
try {
context.log('Start function!');
var pg = require('pg');
const config = {
host: 'example.postgres.database.azure.com',
user: 'postgres#example',
password: 'passwd;',
database: 'test',
port: 5432,
ssl: true
};
var client = new pg.Client(config);
const query = 'insert into test values (\'2\');';
context.log(query);
client.connect(err => {
if (err) {
console.error('connection error', err.stack);
} else {
console.log('connected');
client.query(query, (err, res) => {
if (err) throw err;
console.log(res);
client.end();
})
}
});
} catch (e) {
context.log(e);
} finally {
context.res = {
status: 200,
body: "ok"
};
}
};

NodeJs - Rendering same page after multiple SELECT queries

I have below codes in my index.js file. I can print data of profile table. And i need to print data of resume table also in same (index.njk) page. But i couldn't. I also found a similar question but i am new and couldn't modify those codes according to my project. Can you please help?
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
router = express.Router(),
app = express();
var pg =require('pg');
// DB Connect string
var connect = {
user: 'arslan',
database: 'resumedb',
password: '1984',
host: 'localhost',
port: 5432,
max: 10,
idleTimeoutMillis: 30000,
};
router.get('/', function(req, res){
pg.connect(connect, function(err, client, done, skills){
if(err){
return console.error('errrr', err)
}
//Get Profile Informations
client.query('select id,fname,lname,title,description,profileimage from profile', function(err, result){
if(err){
return console.error('error running query', err);
}
if(result.rows.length > 0) {
res.render('index.njk', {
profileName: result.rows[0].fname,
profileLName: result.rows[0].lname , profileTitle: result.rows[0].title
, profileDesc: result.rows[0].description
, profileImage: result.rows[0].profileimage
});
console.log(result.rows[0].profileimage);
}else {
console.log('No rows found in DB');
}
done()
});
});
});
The best solution for all async stuff is using Promises.
Your code uses the config for a connection pool, but later you dont use a pool, but its often a good idea to use one.
You create a new module db.js to query the db
const pg = require('pg')
const connect = { // Normaly you would use an config file to store this information
user: 'arslan',
database: 'resumedb',
password: '1984',
host: 'localhost',
port: 5432,
max: 10,
idleTimeoutMillis: 30000
}
let pool = new pg.Pool(config)
exports.query = (query, values) => {
return new Promise((resolve, reject) => {
pool.connect(function(err, client, done) {
if (err)
return reject(err)
client.query(query, values, (err, result) => {
done()
if (err)
return reject(err)
resolve(result)
})
})
})
}
exports.queryOne = (query, values) => {
return new Promise((resolve, reject) => {
this.query(query, values).then(rows => {
if (rows.length === 1) {
resolve(rows[0])
} else if (rows.length === 0) {
resolve()
} else {
reject(new Error('More than one row in queryOne'))
}
}).catch(err => {
reject(err)
})
})
}
pool.on('error', function (err, client) {
console.error('idle client error', err.message, err.stack)
})
and then in your route
// ...
const db = require('./db')
router.get('/', function(req, res, next) {
let profileQuery = db.queryOne('select id,fname,lname,title,description,profileimage from profile')
let resumeQuery = db.query('???')
Promise.all([profileQuery, resumeQuery]).then(([profile, resume]) => {
if (!profile) {
return res.status(404).send('Profile not found') // error page
res.render('index.njk', {
profileName: profile.fname,
profileLName: profile.lname,
profileTitle: profile.title,
profileDesc: profile.description,
profileImage: profile.profileimage
})
}).catch(err => {
next(err)
})
})
If you want to make a single query you can use db.query('select 1 + 1').then(rows => { /* your code */}).catch(err => { next(err) }).
Because you often only want one row you can use queryOne. It is returning undefined with no rows, the row you want, or an error for multiple rows
The next() with an error as argument will call the express error handlers. There you can log the error and return 500. You should create your own for that
Please ask if you dont understand something, because it could be complicated for the first time :)

Resources