How to connect Mongo Atlas Database in Lambda function with Mongoose - javascript

I am using Serverless framework to deploy my backend to API Gateway and AWS Lambda.
Here is my serverless.yml for this specific lambda function.
It is a cron job that runs every hour.
cron:
handler: handler.transferHandler
events:
- schedule: rate(1 hour)
Now when I test on localhost it works perfectly. But when I deploy to aws I get the following error:
MongoDB connection error. Please make sure MongoDb is running. { MongoError: failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]
at Pool.<anonymous> (/var/task/node_modules/mongodb-core/lib/topologies/server.js:336:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/pool.js:280:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/connection.js:189:49)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at connectErrorNT (net.js:1021:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
name: 'MongoError',
message: 'failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]' }
Here is my function in my handler.js:
exports.transferHandler = function transferHandler(event, context) {
context.callbackWaitsForEmptyEventLoop = false;
mongoose.connect(mongoString, {useMongoClient: true});
const db = mongoose.connection;
db.on("error", (err) => {
console.log("MongoDB connection error. Please make sure MongoDb is running.", err);
process.exit();
});
db.once('open', () => {
BookingModel
.find({})
.then((bookings) => {
...
})
.catch((err) => {
console.log(err);
})
.finally(() => {
db.close();
});
});
};

After 2 weeks of being stuck on this, I learned that I needed to specify my environment variables in my serverless.yml for it to work. My functions were never connecting to the database because my mongo string was never set in lambda. Hope this helps someone.
provider:
name: aws
runtime: nodejs6.10
stage: production
region: us-west-1
environment:
MONGODB_URL: ${env:MONGODB_URL}
S3_BUCKET: ${env:S3_BUCKET}
S3_BUCKET_REPORT: ${env:S3_BUCKET_REPORT}
STRIPE_CLIENT_ID: ${env:STRIPE_CLIENT_ID}
STRIPE_PUBLIC_KEY: ${env:STRIPE_PUBLIC_KEY}
STRIPE_SECERET_KEY: ${env:STRIPE_SECERET_KEY}
JWT_SECRET: ${env:JWT_SECRET}
SEND_BIRD_TOKEN: ${env:SEND_BIRD_TOKEN}
SEND_BIRD_APP_ID: ${env:SEND_BIRD_APP_ID}
MANDRILL_APIKEY: ${env:MANDRILL_APIKEY}

Related

MSSQL & Node.JS - Failed to connect to WIN-OTGKTVPUIFC:1433

I have a problem when connect to SQL Server.
My config connect SQL Server:
const mssql = require('mssql');
const configMsSql = {
server:"myserver",
port:myport,
user:"username",
password:"pass",
database:"dbname",
options:{
trustServerCertificate: true
}
};
async function connectState(){
const connect = await mssql.connect(configMsSql);
console.log("Connect to SQL successfully!");
return connect;
}
module.exports = connectState();
After run server. mssql throw error:
err = new ConnectionError(err)
^
ConnectionError: Failed to connect to WIN-OTGKTVPUIFC:1433 - 7C250000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1986:
at C:\UIS\SboxNode\node_modules\mssql\lib\tedious\connection-pool.js:70:17
at Connection.onConnect (C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:1020:9)
at Object.onceWrapper (node:events:628:26)
at Connection.emit (node:events:513:28)
at Connection.emit (C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:1048:18)
at Connection.socketError (C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:1399:12)
at C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:2406:25
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to WIN-OTGKTVPUIFC:1433 - 7C250000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1986:
at Connection.socketError (C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:1399:28)
at C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:2406:25
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'ESOCKET',
isTransient: undefined
}
}
Node.js v18.12.1
Although I enabled TCP/IP and field TCP Port used exactly.
I tried to search gg this error but the most answer that "enable TCP/IP".
I spent many time to fix but cant. Help me plzz :(

Why Can't I connect SQL Server to my node js

I'm using the 'mssql' npm package to connect my SQL server to my node JS.
I went through a few questions, but it wasn't solved anywhere.
My SQL Server login credentials are-
server type : Database Engine
Server name : DESKTOP-MPF88ST\KUSHAL
authentication : sql server authentication
login : username
password : password
and the database I wanna get is schoolDB
and my code goes something like this
const sql =require("mssql")
const config = {
login: 'username',
password:'password',
server: 'localhost',
database: "schoolDB",
options : {
enableArithAbort: true
},
port : 1433
}
sql.connect(config, (err) => {
if(err){
console.log(err);
}
else {
console.log("Connected")
}
I have my TCP/IP enabled and set up, SQL Server Browser enabled, but it still throws the error-
ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.<anonymous> (E:\Kushals\server\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:422:26)
at Connection.emit (events.js:315:20)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:12)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:56)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ESOCKET'
}
}
How can I solve it ??
Try this:
const sql = require('mssql/msnodesqlv8')
const pool = new sql.ConnectionPool({
login: 'username',
password:'password',
database: 'schoolDB',
server: 'DESKTOP-MPF88ST\KUSHAL',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
})
pool.connect().then(() => {
//sample query
pool.request().query('select 1 as number', (err, result) => {
console.dir(result)
})
})
Ensure that the TCP/IP protocol is Enabled as it is disabled by default.
Steps:
Go to Computer management
Under Service and Applications -> SQL Server Configuration Manager
-> SQL Server Network configuration -> click on "Protocols for MSSQLSERVER"
You will see TCP/IP section (to enable right click and enable it)

No stream features to proceed using node-xmpp-client

I've installed prosody on an ubuntu AWS server. I have tried using Adium client and swift, but I get the same error indicated in the title. I've tried using node-xmpp-client to create a client but same error.
Node-XMPP client code:
const Client = require('node-xmpp-client');
const options = {
jid: 'test#ec2-18-222-249-134.us-east-2.compute.amazonaws.com',
password: 'password',
host: 'ec2-18-222-249-134.us-east-2.compute.amazonaws.com'
}
const client = new Client(options);
client.once('online', connectionDetails =>{
console.log('We are connected');
console.log(connectionDetails);
});
Error Message:
Error: No stream features to proceed with
at Connection.onStanza (/Users/my-name/BeginXMPP/node_modules/node-xmpp-core/lib/Connection.js:363:17)
at StreamParser.<anonymous> (/Users/my-name/BeginXMPP/node_modules/node-xmpp-
core/lib/Connection.js:231:10)
at StreamParser.emit (events.js:198:13)
at SaxLtx.<anonymous> (/Users/my-name/BeginXMPP/node_modules/#xmpp/streamparser/index.js:69:14)
at SaxLtx.emit (events.js:198:13)
at SaxLtx._handleTagOpening (/Users/my-name/BeginXMPP/node_modules/ltx/lib/parsers/ltx.js:40:12)
at SaxLtx.write (/Users/my-name/BeginXMPP/node_modules/ltx/lib/parsers/ltx.js:159:18)
at StreamParser.write (/Users/my-name/BeginXMPP/node_modules/#xmpp/streamparser/index.js:134:17)
at Connection.onData (/Users/my-name/BeginXMPP/node_modules/node-xmpp-core/lib/Connection.js:310:17)
at Socket.emit (events.js:203:15)
Emitted 'error' event at:
at Client.<anonymous> (/Users/my-name/BeginXMPP/node_modules/node-xmpp-client/lib/Client.js:158:23)
at Connection.emit (events.js:203:15)

Unable to connect to remote MySQL database in Node.js application (DOCKER)?

I have NODE.JS application which works with remote MySQL database. In my local computer (windows 10) application successfully connected to remote MySQL database. I use sequelize library for this task. MySQL database has 40 maximum connection pool for each user. When I run this application in Docker which is in CentOS server I notice error. Application raise error when try to connect to remote MySQL database in Docker container. What can be the reason of this problem for your opinion? How I can fix this problem?
ERROR:
Unable to connect to remote MySQL database: { SequelizeConnectionError: connect ETIMEDOUT
at Utils.Promise.tap.then.catch.err (/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:149:19)
at tryCatcher (/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/node_modules/bluebird/js/release/promise.js:690:18)
at _drainQueueStep (/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (/node_modules/bluebird/js/release/async.js:17:14)
at processImmediate (timers.js:632:19)
name: 'SequelizeConnectionError',
parent:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true },
original:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true } }
JS:
const Sequelize = require('sequelize');
// "max_user_connections" resource for "db_user" user is "40".
const sequelize = new Sequelize('db_name', 'db_user', 'db_password', {
host: 'HOST',
port: '3306',
dialect: 'mysql',
pool: {
max: 15,
min: 5,
idle: 20000,
evict: 15000,
acquire: 30000
}
});
sequelize.authenticate().then(() => {
console.log('Connection to remote MySQL database has been established successfully.');
}).catch(err => {
console.error('Unable to connect to remote MySQL database:', err);
});
module.exports = sequelize;
Dependencies:
"sequelize": "^4.42.0",
"mysql2": "^1.6.4"

Shopify Admin API not working on Google hosted server but works on localhost

My Shopify Admin API not working on Google hosted server but works on localhost. I wonder what am I missing.
I got my order data on localhost but when I upload the code to google server it doesn't work.
I am working on a private app for my shop.
no luck trying to make this works.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const Shopify = require('shopify-api-node');
const shopify = new Shopify({
shopName: 'tinyrabbithole',
apiKey: 'your-api-key',
password: 'your-app-password'
// accessToken: ""
});
shopify.on('callLimits', limits => console.log(limits));
// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.getData = functions.https.onRequest((req, res) => {
shopify.order.list({ limit: 5 })
.then( orders => {
console.log(orders);
return res.status(200).send(orders);
})
.catch( err => {
console.log(err);
return res.status(303).send(err);
})
});
{ RequestError: getaddrinfo ENOTFOUND tinyrabbithole.myshopify.com tinyrabbithole.myshopify.com:443
at ClientRequest.req.once.err (/user_code/node_modules/shopify-api-node/node_modules/got/index.js:182:22)
at ClientRequest.g (events.js:292:16)
at emitOne (events.js:101:20)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:310:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at connectErrorNT (net.js:1025:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
name: 'RequestError',
code: 'ENOTFOUND',
host: undefined,
hostname: 'tinyrabbithole.myshopify.com',
method: 'GET',
path: '/admin/orders.json?limit=5',
protocol: 'https:',
url: undefined }
I'll drop this as an answer instead of leaving it in the comments. If you see a getaddrinfo ENOTFOUND error, first make sure you are on the right payment plan. The free tier doesn't allow outgoing API calls.

Categories