aws / aws-sdk-js

AWS SDK for JavaScript in the browser and Node.js
https://aws.amazon.com/developer/language/javascript/
Apache License 2.0
7.59k stars 1.55k forks source link

MongoDB and Firebase not working with AWS Lambda function #2594

Closed mInzamamMalik closed 5 years ago

mInzamamMalik commented 5 years ago

I am making AWS Lex bot using lambda function and trying to connecting it to database of MongoDB Atlas using "mongoose" and database of firebase using "cloud firestore".But no data is saving to the database and even there is no error giving at cloud watch and not a single console is showing there

I have completed the whole procedure for making cluster on MongoDB Atlas and the process of cloud firestore .

I am runnning the following command to deploy lambda function on AWS Lex bot in both cases of mongodb Atlas and Cloud Firestore:

$ aws lambda update-function-code --function-name Hotel-Booking-Agent --zip-file fileb://index.zip

Below is the code for connecting mongodb atlas with lambda function

'use strict';
var mongoose = require('mongoose');
var dbURI = "mongodb+srv://author:******@cluster0-geoiq.mongodb.net/test?retryWrites=true";
mongoose.connect(dbURI, { useNewUrlParser: true })
    .catch((e) => {
        console.log("catch error: ", e)
    })
mongoose.connection.on('error', function (err) {//any error
    console.log('Mongoose connection error: ', err);
    process.exit(1);
})
mongoose.connection.on('connected', function () {//connected
    console.log("Mongoose is connected");
})

mongoose.connection.on('disconnected', function () {//disconnected
    console.log("Mongoose is disconnected");
    process.exit(1);
});
console.log("reach here")
var userSchema = new mongoose.Schema({
    "name": { type: String, required: true },
    "email": { type: String, required: true },
    "Detail": { type: String, required: true }
},
    {
        collection: "user1"
    });
exports.handler = (event, context, callback) => {

    try {
        console.log(`request received for userId=${event.userId}, intentName=${event.currentIntent.name}`);
        var slots = event.currentIntent.slots;
        var noOfPeople = slots.noOfPeople;
        var noOfRoom = slots.noOfRoom;
        var roomKind = slots.roomKind;
        var subject = slots.subject;
        var name = slots.name;
        var email = slots.email;
        switch (event.currentIntent.name) {
            case 'Hotel_Booking':
                var userModel = mongoose.model("user", userSchema);
                var newUser = new userModel({
                    "name": name,
                    "email": email,
                    'Detail': `You have booked ${noOfRoom} rooms for ${noOfPeople} people in ${roomKind} category`
                })
                 newUser.save((dataSaved) => {
                    console.log("datasaved", dataSaved)
                })
                context.succeed({
                    "dialogAction": {
                        "type": "Close",
                        "fulfillmentState": "Fulfilled",
                        "message": {
                            'contentType': 'PlainText',
                            'content': `Okay, ${name} I have book  ${noOfRoom} rooms for ${noOfPeople} people in ${roomKind} category`
                        }
                    }
                })
                break
                        default:

                context.succeed({

                    "dialogAction": {
                        "type": "Close",
                        "fulfillmentState": "Fulfilled",
                        "message": {
                            'contentType': 'PlainText',
                            'content': `Can't understand`
                        }
                    }
                })
        }
    }
    catch (err) {
        context.succeed(err);
    }
}; 

The data must be saved on database as in the code.Also that AWS Lex bot is giving a response as directed in lambda function but there is no data showing in database of MongoDB Atlas. Snap of mongodb Atlas Database

Here is the code for connecting firestore with lambda function

'use strict';
var admin = require("firebase-admin");
var serviceAccount = require("./agent-e2634-firebase-adminsdk-0n8na-40c5078975.json");
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://agent-e2634.firebaseio.com"
});
const db = admin.firestore();
exports.handler =  (event, context, callback) => {
    try {
        console.log(`request received for userId=${event.userId}, intentName=${event.currentIntent.name}`);
        var slots = event.currentIntent.slots;
        var noOfPeople = slots.noOfPeople;
        var noOfRoom = slots.noOfRoom;
        var roomKind = slots.roomKind;
        var subject = slots.subject;
        var name = slots.name;
        var email = slots.email;
        switch (event.currentIntent.name) {
            case 'Hotel_Booking':
                var docRef = db.collection('users').doc('info');

                var setAda = docRef.set({
                    'name': name,
                    'email': email,
                    'content': `Okay, ${name} I have book  ${noOfRoom} rooms for ${noOfPeople} people in ${roomKind} category`
                });
                db.collection('users').get()
                    .then((data) => {
                        context.succeed({
                            "dialogAction": {
                                "type": "Close",
                                "fulfillmentState": "Fulfilled",
                                "message": {
                                    'contentType': 'PlainText',
                                    'content': `Okay, ${name} I have book  ${noOfRoom} rooms for ${noOfPeople} people in ${roomKind} category`
                                }
                            }
                        })
                        console.log(doc.id, '=>', data);
                    })
                    .catch((err) => {
                        console.log('Error getting documents', err);
                    });
                break
                        default:

                context.succeed({

                    "dialogAction": {
                        "type": "Close",
                        "fulfillmentState": "Fulfilled",
                        "message": {
                            'contentType': 'PlainText',
                            'content': `Can't understand`
                        }
                    }
                })
        }
    }
    catch (err) {
        context.succeed(err);
    }
}

When i deploy the above code the bot returns the following error:

An error has occurred: Invalid Lambda Response: Received error response from Lambda: Unhandled

the same code is working fine without connecting to database and even no collection and docs are making on cloud firestore.

jawwadturabi commented 5 years ago

+1

srchase commented 5 years ago

@malikasinger1

Is this an issue pertaining to the JavaScript SDK? This looks like a general Lambda question.

mInzamamMalik commented 5 years ago

The same mongodb code is working in working in express server but it is not working in aws lambda, what is the reason?

mInzamamMalik commented 5 years ago

Actually .then part of the code never executes in aws Lambda

mInzamamMalik commented 5 years ago

Please let me know the correct person to report only if this problem is not relevant to this repo

AllanZhengYP commented 5 years ago

Hi, @malikasinger1

I don't think this is an AWS SDK specific issue. Maybe you can turn to Lambda forum to ask for help.

Clearly, as the response suggests, you have unhandled exception in your Lambda execution. You can try sam cli to deploy and manage the whole stack of your lambda function. It also offers ability to do local debugging.

mInzamamMalik commented 5 years ago

I have only one function in total, which is acting as webhook of amazon lex

mInzamamMalik commented 5 years ago

I am unable to create a new ticket in the forum, where is the button to create a new ticket in forum?

mInzamamMalik commented 5 years ago

image

AllanZhengYP commented 5 years ago

@malikasinger1 Have you tried 'Post New Thread'?

no-response[bot] commented 5 years ago

This issue has been automatically closed because there has been no response to our request for more information from the original author. With only the information that is currently in the issue, we don't have enough information to take action. Please reach out if you have or find the answers we need so that we can investigate further.

lock[bot] commented 5 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs and link to relevant comments in this thread.