I am using Sequelize with postgres database.
But authenticate() function does not send any response(whether it is success or failed)
Here is my code.
const connection = new Sequelize('BLIG', 'postgres', 'admin', {
host: 'localhost',
dialect: 'postgres',
define: {
timestamps: false
}
});
app.use('/', (req, res, next) => {
console.clear();
connection.authenticate()
.then(
() => { console.log("Database connected..."), next() },
error=>{console.log("Database connection error",error)}
)
.catch(err => { console.log('database connection error', err), res.redirect('/error') });
})
If anyone knows this issue, help me please.
update your "pg" node package to 8.5.1 or above version using
npm i pg#8.5.1
Related
I was trying to perform postgres queries using node but for some reason is not fetching the data from postgres.
See my database.js below:
const { Client } = require('pg');
const PORT = process.env.PORT || 3000;
const client = new Client({
host: 'localhost',
port: PORT,
user: 'postgres',
password: 'postgres',
database: 'ecommerce'
})
client.connect();
client.query('select * from customers', (err, result) => {
if (!err) {
console.log(result.rows)
} else {
console.log(err)
}
client.end();
})
Please note that the customers table is a valid table in my ecommerce database.
Any help would be appreciated.
You should wait the client to connect.
See the docs here
const { Client } = require('pg')
const client = new Client()
client
.connect()
.then(() => console.log('connected'))
.catch(err => console.error('connection error', err.stack))
Instead of console.log('connected'), write your query.
My nodejs API runs fine for few hours then API does not return data to client. Once I debug I found that TypeOrm Unable to query data from remote postgres server even though postgres server is Connected. Query in Nodejs application die with no error.
I can query data from remote postgres DB from pgAdmin.
The app.ts code
const conn = await createConnection({
host: process.env.TYPEORM_HOST,
password: process.env.TYPEORM_PASSWORD,
type: 'postgres',
username: process.env.TYPEORM_USERNAME,
database: process.env.TYPEORM_DATABASE,
port: Number(TYPEORM_PORT),
logging: TYPEORM_LOGGING === 'true' ? true : false,
synchronize: TYPEORM_SYNCHRONIZE === 'true' ? true : false,
entities: [UserEntity],
});
console.log(conn.options.database);
////#### Middleware Section ####/////
const apolloServer = new ApolloServer({
schema: await CreateSchema(),
subscriptions: {
path: `${ENDPOINT_PATH}`,
},
uploads: false,
//tracing: true,
context: ({ req, res }: any) => ({
req,
res,
...dataLoaderInject,
}),
});
const app = Express();
const whitelist: any = process.env.ENDPOINT_CORS?.split(',').map((x) =>
x.trim()
);
var corsOptions = {
origin: function (origin: any, callback: any) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(null, false);
}
},
credentials: true,
};
app.use(cors(corsOptions));
app.use(graphqlUploadExpress({ maxFileSize: 500000000, maxFiles: 50 }));
app.use(cookieParser());
apolloServer.applyMiddleware({ app, cors: false, path: ENDPOINT_PATH });
const httpServer = http.createServer(app);
apolloServer.installSubscriptionHandlers(httpServer);
httpServer.listen(ENDPOINT_PORT, () => {
//Register jobScheduler here
JobSchedulerService.sendReminder();
console.log(
`Server started at ${ENDPOINT}:${ENDPOINT_PORT}${ENDPOINT_PATH}`
);
});
POST request where TypeOrm fails to return results from remote postgres server.
app.post('/user', async (req, res) => {
let token = req.cookies.UserCookie;
if (!token) {
console.log('token is not valid ' + token);
return res.send({ ok: false, accessToken: '' });
}
let payload: any;
try {
payload = verify(token, process.env.REFRESH_TOKEN_SECRET!);
} catch (err) {
console.log(err);
return res.send({ ok: false, accessToken: '' });
}
const user = await
getRepository(UserEntity)
.createQueryBuilder()
.where('"ID"=:ID', { ID: payload.userID })
.getOne() // request die here , no error , does not respond anything
.catch( err => {
console.log(err, "User Query error")
})
if (!user) {
console.log('User not found');
return res.send({ ok: false, accessToken: '' });
}
Stack version
Postgres 12
Nodejs : v12.16.3
npm : 6.14.4
"pg": "^8.3.3"
"typeorm": "^0.2.26",
"express": "^4.17.1",
"node-cron": "^2.0.3",
Your response will be much appreciated Thank you.
I'm writing a lambda function to connect to a postgress DB that I have on an EC2 instance. I've been utilizing the 'pg' library for connecting as found in their documentation, however, my function keeps skipping over the establish connection piece of my method and just continuing and exiting without accomplishing anything.
const client = new Client({
user: 'user',
host: 'xxxx.xxx.xxxx',
database: 'dbname',
password: 'password',
port: 5432,
})
client.connect(err => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
}
})
client.query('select count(*) from "Product"', (error, results) => {
if (error) {
console.log("Error when trying to query");
throw error
}
console.log(results.rows)
})
I'm going exactly by the methods that the 'pg' documentation says (https://node-postgres.com/features/connecting), but can't figure out what is going wrong here. I'm using serverless with nodejs12.x for this function.
You are not waiting for the connection to be established before querying. Try this:
const client = new Client({
user: 'user',
host: 'xxxx.xxx.xxxx',
database: 'dbname',
password: 'password',
port: 5432,
})
return client.connect(err => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
return client.query('select count(*) from "Product"', (error, results) => {
if (error) {
console.log("Error when trying to query");
throw error
}
console.log(results.rows)
})
}
})
Although, if your can, create a promise chain as it is probably easier to manage like so:
const client = new Client({
user: 'user',
host: 'xxxx.xxx.xxxx',
database: 'dbname',
password: 'password',
port: 5432,
})
return client.connect().then(()=>{
return client.query('select count(*) from "Product"')
}).then((results)=>{
console.log(results.rows)
}).catch((err)=>{
console.error('error', err.stack? err.stack : err)
})
I say use a promise chain if you can because Im not sure what the pg library returns on connect and query..
Hope this helps!
I'm trying to connect from nodeJS to Sql Server on my local machine. When I run the app the following error is raised:
Login failed for user \'admin\'.', code: 'ELOGIN' },
Here's my connection details:
const sql = require('mssql');
const config = {
host:'localhost',
user:'admin',
password:'password',
database:'database',
server:'localhost\\SQLEXPRESS'
}
const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to localhost '+ config.database +' database');
return pool;
})
.catch(err => console.log('Database connection failed. Error: ', err));
module.exports = {
sql, poolPromise
}
This PoolPromise is then used in some Repository files to manage the data from database like this:
const { poolPromise } = require('./pool');
module.exports = {
create: async function (name) {
const pool = await poolPromise;
return await pool.request()
.input('nameParameter', name)
.query('INSERT INTO dbo.table(nombre) VALUES (#nameParameter)')
.then(result => {
console.log(result);
}).catch(function(err) {
console.log(err.message);
});
},
I've tried installing the msnodesqlv8 module, but it's not working. My npm version is npm: '6.4.1'.
I'm losing my mind trying to solve this. Any ideas?
const sql = require('mssql')
const config = {
user: 'root',
password: 'root',
server: 'localhost',
database: 'test'
}
const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
module.exports = {
sql, poolPromise
}
const express = require('express')
const router = express.Router()
const { poolPromise } = require('./pool')
router.get('/', async (req, res) => {
try {
const pool = await poolPromise
const result = await pool.request()
.input('input_parameter', sql.Int, req.query.input_parameter)
.query('select * from mytable where id = #input_parameter')
res.json(result.recordset)
} catch (err) {
res.status(500)
res.send(err.message)
}
})
module.exports = router
Please use instance and server
dialect: 'mssql',
port: 1433,
options: {
// If you are on Microsoft Azure, you need encryption:
encrypt: true,
database: process.env.SQL_DATABASE , //update me
instanceName: process.env.SQL_INSTANCE
}
So, I use the pg module in node 8.11.1 / express 4.16.3 / pg 7.4.2
I try to use the pool for my front-end (just selects) and the examples are somewhat confusing.
In connecting it uses just a new Pool and then it shows that I have to do pool.end()
const pool = new Pool({
user: 'dbuser',
host: 'database.server.com',
database: 'mydb',
password: 'secretpassword',
port: 3211,
})
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res)
pool.end()
})
I made my code like that and it prints Error: Cannot use a pool after calling end on the pool If I do the same query a couple of times. So, no pool.end()
In queries there is no disconnection in the examples (?)
I finally made my code like the pooling. It shows the pool.on('error', (err, client) => { function and then it uses client.release() in the pool, since "pool.query delegates directly to client.query internally" I guess?
So, what is the right way to use pool in the pg and how to disconnect after each query or failure? I came up with this
const pool = new pg.Pool({
user: 'user',
host: 'localhost',
database: 'myProject',
password: 'secret',
port: 5432
});
pool.on('error', (err, client) => {
console.error('error on client', err, 'on client' , client);
process.exit(-1);
});
app.get('/', (req, res)=>{
pool.connect()
.then(client => {
return client.query('select name from table')
.then(resolved => {
client.release();
res.render('index',{'testData': resolved.rows});
})
.catch(e => { //return client.query
client.release();
res.render('index',{'errorData': e});
})
.catch(e => { //pool.connect()
client.release();
res.render('index',{'errorData': e});
})
})
});
I dont know if this can be shorter in any way. Like, for example if the catch(e => { ////pool.connect()... is needed or it is covered by pool.on('error', (err, client) => {...
Also, it could be a lot sorter if it was like
const pool = new pg.Pool({
user: 'user',
host: 'localhost',
database: 'myProject',
password: 'secret',
port: 5432
});
app.get('/', (req, res)=>{
pool.query('...')
.then(resolved => {
pool.end();// pool disconnect ???
res.render('index',{
'testData': resolved.rows
});
})
.catch(e => {
pool.end();// pool disconnect ???
res.render('index',{
'testData': e
});
})
});
But I dont know if this is right because there is no pool.connect , there is no client returned from that connection and there is no function to disconnect the pool (only to end it, that ends up again with Error: Cannot use a pool after calling end on the pool).
Please advice on the right pool usage and syntax
Thanks
I ran into this kind of Problem too with another npm package for mssql.
After some trail and error i decided to go for a singelton (static would also be possible) class which handles the connection.
Now you just have to call one function before each query in order to create a new connection pool or receive the present one.
Something like this:
let _this = {};
let connectionPool = null;
function getConnection(){
if(connectionPool){
return connectionPool
} else {
connectionPool = new pg.Pool({
user: 'user',
host: 'localhost',
database: 'myProject',
password: 'secret',
port: 5432
});
return connectionPool;
}
}
function closeConnection(){
// close connection here
}
_this.getConnection = getConnection;
_this.closeConnection = closeConnection;
module.exports = _this;