0

I am struggling to configure back end using Lamda function, currently i have full stack application and locally it is working fine. I have also managed to deploy the mysql server(aws rds) and front end page(S3 bucket) and when i try to deploy the backend (Lamda function) i got a bit confused with it.

Really appreciate if anyone can advise or give any pointer here for my below questions please.

Q1- I have dig around and can see that i can use export.handler but here i am having two API calls, do i need to make two saperate function and if so then do i need to upload two zip files with all the other dependencies in both the files

Q2- is it the correct way to connect from Lamda function to rds DB as below , am i still able to do the same connect.query commads.... to use mysql(it is currently working fine if i access aws-rds from locally)


     let connection = mysql.createConnection({
          host: "root.cjfdyreioui1.eu-west-2.rds.amazonaws.com", // here i connect to rds aws
          user: "root",
          password: "abc1234",
       
          database: "join_us",
          insecureAuth: true,
        });

-Snippet of Backend-code server.js that i zipped around 30mb (do i need to keep index.js filename instead)


    const express = require("express");
    const mysql = require("mysql");
    const jwt = require("jsonwebtoken");
    const auth = require("./verifyTokenExisting");
    const authNew = require("./verifyTokenNew");
     const cors = require("cors");
    const cookieParser = require("cookie-parser");
    const pdf = require("html-pdf");
    const pdfTemplate = require("./documents/pdfTemplate");
    const fs = require("fs");
    
    const app = express();
    app.use(express.json());
    app.use(cookieParser());
    
    
    app.use(
      cors({
        credentials: true, // for cookies
        origin: "http://localhost:3000",
        optionsSuccessStatus: 200,
      })
    );
    let connection = mysql.createConnection({
      host: "root.cjfdyreioui1.eu-west-2.rds.amazonaws.com", // here i connect to rds aws
      user: "root",
      password: "abc1234",
   
      database: "join_us",
      insecureAuth: true,
    });
    
    
    
    //!  when clicked on signin page to verify after signin/
    
    app.post("/api/verifyifloginalready", (req, res) => {
      let token = req.cookies.yogaoutlet_access_token;
      //
    
      if (!token) {
        return res.status(401).end();
      }
    
      let decodepayload;
    
      try {
        decodepayload = jwt.verify(token, "lllfasdgfdadsfasdfdasfcadsf");
    
      } catch (error) {
        if (error instanceof jwt.JsonWebTokenError) {
       
          // if invalid token
          res.status(401).end();
        } else {
          res.status(400).end();
        }
      }
      connection.query("SELECT * FROM  users WHERE email=?;", [decodepayload.email], function (err, results) {
        res.json(results);
      });
    });
    
    ////!  LOGIN & LOGOUT
    
    app.post("/api/newuser", (req, res) => {
      let x1 = req.body;
      
      if (req.body.logout === false) {
        connection.query("SELECT * FROM  users WHERE email=?;", [x1.email], function (err, results) {
        
          if (err) console.log("13333", err);
          else {
            if (results[0].email && results[0].password) {
         
    
              if ((results[0].password == x1.password && results[0].userloginStatus == true) || (results[0].password == x1.password && results[0].userloginStatus == null)) {
                const payload = { email: results[0].email };
                 const token = jwt.sign(payload, "lllfasdgfdadsfasdfdasfcadsf");
                 res.cookie("yogaoutlet_access_token", token, {
                  maxAge: 25 * 24 * 60 * 60 * 1000,
                  httpOnly: true, // it will enable on frotend-javascript to not have access to cokkies
                  
                });
    
                res.status(200).end();
    
                  connection.query(
                  "UPDATE  users SET userloginStatus=? WHERE email=?",
                   
                  ["1", results[0].email],
                  function (err, results) {
                    if (err) throw err;
                    console.log(results);
                  }
                );
              } else {
                res.json({
                  data: "invalid  password",
                });
              }
            } else res.redirect("http://localhost:3000/about");
          }
        });
      } else {
        
        const payload = { email: req.body.email };
        console.log("339x", payload);
        const token = jwt.sign(payload, "lllfasdgfdadsfasdfdasfcadsf");
    
        res.clearCookie("yogaoutlet_access_token");
    
        res
          .json({
            data: "User Logged out",
          })
          .end();
      }
    });

1 Answer 1

1

Q1: Yes, you use export.handler because Lambda needs an entry point. See the AWS Lambda developer guide here: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html

But Lambda can't run a server so your server.js file has to be adapted. You need something else to handle connections from clients. Perhaps API Gateway fits the bill.

When deploying you upload a ZIP archive: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html

Q2: AWS Lambda running a Node function which uses RDS is not really my forte. But if your server connects, executes transactions and then disconnects quickly, it shouldn't be a problem. In any case, AWS CloudWatch will help you if you experience problems.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.