-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
57 lines (49 loc) · 1.56 KB
/
app.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
53
54
55
56
57
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
require("dotenv").config();
var indexRouter = require("./routes/index");
var apiRouter = require("./routes/api");
var apiResponse = require("./helpers/apiResponse");
var cors = require("cors");
// DB connection
var MONGODB_URL = process.env.MONGODB_URL;
var mongoose = require("mongoose");
mongoose.connect(MONGODB_URL, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => {
//don't show the log when it is test
if(process.env.NODE_ENV !== "test") {
console.log("Connected to %s", MONGODB_URL);
console.log("App is running on %s... \n",app.get("port"));
console.log("Press CTRL + C to stop the process. \n");
}
})
.catch(err => {
console.error("App starting error:", err.message);
process.exit(1);
});
var db = mongoose.connection;
var app = express();
//don't show the log when it is test
if(process.env.NODE_ENV !== "test") {
app.use(logger("dev"));
}
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
//To allow cross-origin requests
app.use(cors());
//Route Prefixes
app.use("/", indexRouter);
app.use("/api/", apiRouter);
// throw 404 if URL not found
app.all("*", function(req, res) {
return apiResponse.notFoundResponse(res, "Page not found");
});
app.use((err, req, res) => {
if(err.name == "UnauthorizedError"){
return apiResponse.unauthorizedResponse(res, err.message);
}
});
module.exports = app;