-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (44 loc) · 1.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
require("dotenv").config();
const express = require("express");
const serverless = require("serverless-http");
const cors = require("cors");
const mongoose = require("mongoose");
const songsRoute = require("./routes/songsRoute");
const authRoute = require("./routes/authRoute");
const reportsRoute = require("./routes/reportsRoute");
const app = express();
// https://awstip.com/deploying-an-express-js-mongodb-application-on-aws-lambda-with-serverless-framework-289c39891a3f
// forever thankfull mr Afeef Razick
app.use(async (req, res, next) => {
if (mongoose.connection.readyState === 0) {
await mongoose
.connect(process.env.MONGO_URI)
.then(() => {
console.log("Connected to MongoDB server successfully");
})
.catch((err) => {
console.log(err);
});
} else {
console.log(
"Connection already established, reusing the existing connection"
);
}
next();
});
app.use(express.json());
// catch bad json syntax
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && "body" in err)
return res.status(400).json({ status: 400, message: err.message });
next();
});
app.use(cors());
app.use("/songs", songsRoute);
app.use("/login", authRoute);
app.use("/reports", reportsRoute);
const handler = serverless(app);
module.exports.handler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false; // caches mongoose connections inbetween requests
return await handler(event, context);
};