forked from exemplar-codes/online-shop-express-ejs-mvc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
62 lines (50 loc) · 1.79 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
58
59
60
61
62
const path = require("path");
const {
mongoConnect,
getDb,
prepopulateIrrelevantSampleData,
} = require("./util/database.js");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const adminRoutes = require("./routes/admin");
const shopRoutes = require("./routes/shop");
const errorController = require("./controllers/error");
const User = require("./models/User");
const Product = require("./models/Product");
// app.set('view engine', 'pug');
// app.set('views', 'views'); // not needed for this case, actually
app.set("view engine", "ejs");
app.set("views", "views"); // not needed for this case, actually
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
app.use(cors());
// mock authentication, i.e. get user who's making the request
app.use(async (req, res, next) => {
// req.user = await User.findById(1);
const [firstUser = null] = await User.fetchAll(); // as of now, this is the sample user
req.user = firstUser;
console.log("Mock authentication success", {
email: firstUser?.email,
id: firstUser?._id,
});
next();
});
app.get("/try", async (req, res, next) => {
await new Promise((r) => setTimeout(r, 1000));
return res.json({ time: new Date().toLocaleTimeString() });
});
app.use("/admin", adminRoutes);
app.use(shopRoutes);
app.use(errorController.get404);
// express code
// start express from inside the mongoConnect callback
mongoConnect(async (client) => {
await prepopulateIrrelevantSampleData();
const firstSampleUser = await User.prepopulateUsers();
await Product.prepopulateProducts(firstSampleUser);
console.log("Pre-scripts finished execution");
console.log("------------------------------");
app.listen(3000);
});