Connection timed out on AWS Lambda - node.js

I'm trying to connect to my DB from Lambda as follows:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'user', 'password', {
host: 'host',
port: '5432',
dialect: 'postgres'
});
const Survey = sequelize.define('survey', {
id: Sequelize.UUID
})
const a = await Survey.findAll({
where:{
share_id: '4bdd12bc-35f3-4c44-8478-741106757bd2',
},
limit:10
})
}
when I try to test this code I'm getting an error saying that it timed out:
"errorMessage": "2022-09-30T10:56:32.069Z c89d7b89-b4b1-4283-8e5e-679ca2de5974 Task timed out after 10.01 seconds"
I tried using different libraries too, like pg, massive, but got the same response from all of them.

Related

Redis connection in broken state: connection timeout exceeded. It might have been processed Nodejs + Async-redis

Am trying to connect to AWS redis elastic cache, but i keep getting this error all the time. I am not sure what i am doing wrong here, any help is greatly appreciated. Here's my code
async function testRedis(){
try{
const asyncRedis = require("async-redis");
const client = asyncRedis.createClient({
port: 6379,
host: 'myHost',
auth_pass: redisPassword,
connect_timeout: 900,
enable_offline_queue: false
})
const response = await client.set("test", "response");
const redisResp = await client.get("test");
const connStatus = client.quit()
console.log('connection status::', connStatus)
} catch (err) {
console.log(err)
}
}
I had the same issue. My host didn't an provide IP address for host option so I fixed it by using a connection string: [redis[s]:]//[[user][:password#]][host][:port][/db-number][?db=db-number[&password=bar[&option=value]]]
Should look something like:
const connectionString = 'rediss://username:password#url-to-your.redis.db.server.com:2500'
const client = asyncRedis.createClient(connectionString);
Async redis is a wrapper over Node Redis: https://www.npmjs.com/package/redis
Check out the docs for more info.

ConnectionError: Failed to connect to localhost:3306 - Cannot call write after a stream was destroyed in node.js i am getting error while running

In node.js I am getting error while running index.js file:
var dbConfig = {
user: "test",
password: "***",
server: "localhost",
database: "hello",
port: parseInt("3306"),
options: {
"enableArithAbort": true
}
};
app.get("/CodList", function(_req ,_res){
var Sqlquery = "select * from CodeList";
QueryToExecuteInDatabase(_res, Sqlquery);
});
How to fetch the records from dtabase using node.js?
I found this way to solve this problem :
options: {
encrypt:false
}
full :
const msSqlConfig={
server:SQL_SERVER_NAME,
port:SQL_PORT,
user:${SQL_USER_NAME},
password:${SQL_PASSWORD},
database:SQL_DB_NAME,
options: {
encrypt:false
}
}

Login failed using Express and Sequelize with SQL Server

I am trying to use Sequelize (v 5.21.13) to connect to my SQL Server database in my Expressjs app.
dbconfig.js
var dbConfig = {
server: process.env.DB_HOST,
authentication: {
type: 'default',
options: {
userName: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD
}
},
options: {
database: process.env.DB_NAME
}
};
module.exports = dbConfig;
index.js:
const dbConfig = require('./dbConfig');
const Sequelize = require('sequelize');
const connection = new Sequelize(
dbConfig.options.database,
dbConfig.authentication.options.userName,
dbConfig.authentication.options.password,
{
host: dbConfig.server,
dialect: 'mssql',
}
);
connection.sync().then(() => {
console.log('Connected!');
}).catch((e) => {
console.log('Error:\n', e);
});
Now the thing is that each time I run the server, I get this error
AccessDeniedError [SequelizeAccessDeniedError]: Login failed for user 'master'.
I have also tried adding additional properties to the new Sequelize() like the following with no luck.
dialectOptions: {
instanceName: 'instance',
options: {
encrypt: true,
trustServerCertificate: true,
requestTimeout: 30000
}
}
I even tried changing the password to a very simple one with no special characters, connection with Datagrip works after changing but not using Sequelize.
Everything on the dbconfig object is correct so I don't see what the issue might be.
Solved it. I was putting the the db instance id as the database name, I realized that the database name was different. Changed it and I'm now connected through Sequelize.

How to handle error of closed MySQL connection in Node.js?

I've built a Node.js API that connects to a MySQL database. I use node-mysql2 as driver. The API and the database run in separate Docker container. At some point after deployment in a Kubernetes cluster I get the following error:
Error: Can't add new command when connection is in closed state
at PromiseConnection.query (/usr/src/app/node_modules/mysql2/promise.js:92:22)
I wonder why this error happens and how to catch and handle it using Node.js. These are code snippets of my Node.js API:
const mysql = require('mysql2/promise')
...
async function main() {
try {
const client = await mysql.createConnection({
host: DATABASE_HOST,
port: DATABASE_PORT,
user: DATABASE_USERNAME,
password: DATABASE_PASSWORD,
database: DATABASE_NAME
})
client.on('error', error => {
process.stderr.write(`${error.code}\n`) // PROTOCOL_CONNECTION_LOST
process.stderr.write(`An error occurred while connecting to the db: ${error.message}\n`)
process.exit(1)
})
} catch (error) {
process.stderr.write(`Error while creating db connection: ${error.code}\n`)
}
...
}
...
main().catch(err => {
process.stderr.write(`Error message: ${err.message}\n`)
process.exit(1)
})
Do you have an idea how to handle this error?
Do you close the connection after finishing with it?
client.end();
Also considered using a pool?
const pool = mysql.createPool({
host: DATABASE_HOST,
user: DATABASE_USERNAME,
database: DATABASE_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
More info about pools: https://github.com/sidorares/node-mysql2#using-connection-pools

How to connect KnexJS with database Oracle?

I have connection but i do not know if it exists in connection the key odbc... but even if i throw it away the error informed below persists
const knex = require('knex');
// connection database
const dbmdlog = knex({
client: 'oracle',
connection: {
host: 'localhost',
user: 'root',
password: 'root',
database: 'mydb',
odbc: 'MYDB'
}
});
module.exports = dbmdlogp;
I'm doing a select simple in a collun
But always return error:
Unhandled rejection TypeError: _this2.driver.connect is not a function
at /var/www/html/myapp/node_modules/knex/lib/dialects/oracle/index.js:143:21
at Promise._execute (/var/www/html/myapp/node_modules/bluebird/js/release/debuggability.js:299:9)
at Promise._resolveFromExecutor (/var/www/html/myapp/node_modules/bluebird/js/release/promise.js:481:18)
at new Promise (/var/www/html/myapp/node_modules/bluebird/js/release/promise.js:77:14)
at Client_Oracle.acquireRawConnection (/var/www/html/myapp/node_modules/knex/lib/dialects/oracle/index.js:142:12)
at Object.create (/var/www/html/myapp/node_modules/knex/lib/client.js:231:16)
at Pool._createResource (/var/www/html/myapp/node_modules/generic-pool/lib/generic-pool.js:326:17)
at Pool.dispense [as _dispense] (/var/www/html/myapp/node_modules/generic-pool/lib/generic-pool.js:314:12)
at Pool.acquire (/var/www/html/myapp/node_modules/generic-pool/lib/generic-pool.js:392:8)
at /var/www/html/myapp/node_modules/knex/lib/client.js:281:19
at Promise._execute (/var/www/html/myapp/node_modules/bluebird/js/release/debuggability.js:299:9)
at Promise._resolveFromExecutor (/var/www/html/myapp/node_modules/bluebird/js/release/promise.js:481:18)
at new Promise (/var/www/html/myapp/node_modules/bluebird/js/release/promise.js:77:14)
at Client_Oracle.acquireConnection (/var/www/html/myapp/node_modules/knex/lib/client.js:272:12)
at /var/www/html/myapp/node_modules/knex/lib/runner.js:200:30
at Promise._execute (/var/www/html/myapp/node_modules/bluebird/js/release/debuggability.js:299:9)
A combination of knex and OracleDB works fine. Here are packages from package.json: "knex": "0.13.0", "oracledb": "1.13.1"
And the knex call:
var conn = knex({
client: 'oracledb',
connection: {
host: config.oracle.host,
user: config.oracle.user,
password: config.oracle.password,
database: config.oracle.database,
}
});
In case someone needs to pass a connection string. Please note however, the details inside the connection string will need to match your own environment.
const oracledb = require("oracledb");
oracledb.initOracleClient({ libDir: "C:\\oracle\\instantclient_12_1" });
const knex = require("knex")({
client: "oracledb",
connection: {
user: "YOUR_USER",
password: "YOUR_PASSWORD",
connectString: "(DESCRIPTION=(CONNECT_TIMEOUT=10)(RETRY_COUNT=3)(SOURCE_ROUTE=yes)(ADDRESS_LIST=(LOAD_BALANCE=on)(ADDRESS=(PROTOCOL=tcp)(HOST=your2.domain.com)(PORT=11529))(ADDRESS=(PROTOCOL=tcp)(HOST=your2.domain.com)(PORT=11529)))(ADDRESS_LIST=(FAILOVER=on)(LOAD_BALANCE=off)(ADDRESS=(PROTOCOL=tcp)(HOST=your3.domain.com)(port=1521))(ADDRESS=(PROTOCOL=tcp)(HOST=your4.domain.com)(port=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=YOUR_SERVICE.your5.domain.com)))",
requestTimeout: 100
},
fetchAsString: ["number", "clob"]
});
knex.select().from("TABLE1").asCallback(function(err, rows){
if(err)
console.log(err);
else
console.table(rows);
});

Resources