forked from keikaavousi/fake-store-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·79 lines (68 loc) · 1.96 KB
/
server.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//initializes
const mongoose = require("mongoose");
const express = require("express");
const cors = require("cors");
const path = require("path");
const dotenv = require("dotenv");
const dotenvExpand = require("dotenv-expand");
const myEnv = dotenv.config();
dotenvExpand.expand(myEnv);
//app
const app = express();
//port
const port = process.env.PORT || 6400;
//routes
const productRoute = require("./routes/product");
const homeRoute = require("./routes/home");
const cartRoute = require("./routes/cart");
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
//middleware
app.use(cors());
app.use(express.static(path.join(__dirname, "/public")));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
//view engine
app.set("view engine", "ejs");
app.set("views", "views");
app.disable("view cache");
app.use("/", homeRoute);
app.use("/products", productRoute);
app.use("/carts", cartRoute);
app.use("/users", userRoute);
app.use("/auth", authRoute);
//mongoose
mongoose.set("useFindAndModify", false);
mongoose.set("useUnifiedTopology", true);
mongoose
.connect(process.env.DATABASE_URL, { useNewUrlParser: true })
.then(() => {
app.listen(port, () => {
console.log("connect");
const Product = require("./model/product");
// find if product collection is empty
Product.find()
.then((products) => {
if (products.length == 0) {
// if empty, insert products
const products = require("./data/products");
Product.insertMany(products)
.then((products) => {
console.log("Products inserted");
})
.catch((err) => {
console.log(err);
});
} else {
console.log("Products exist");
}
})
.catch((err) => {
console.log(err);
});
});
})
.catch((err) => {
console.log(err);
});
module.exports = app;