-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathserver.js
89 lines (72 loc) · 2.41 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
80
81
82
83
84
85
86
87
88
89
const express = require("express");
const mongoose = require("mongoose");
const logger = require("morgan");
const path = require("path");
require("dotenv").config();
const cors = require("cors");
// our routes
const productRouter = require("./routes/api/product");
const categoryRouter = require("./routes/api/category");
const usersRouter = require("./routes/api/users");
const cartRouter = require("./routes/api/cart");
const wishlistRouter = require("./routes/api/wishlist");
const addressRouter = require("./routes/api/address");
const orderRouter = require("./routes/api/order");
const permissionsRouter = require("./routes/api/permission");
const app = express();
// for body-parser middleware
app.use(express.json());
//cors middleware
app.use(cors());
// morgan logger for dev
app.use(logger("dev"));
//make our upload an accesable folder
app.use("/uploads", express.static("uploads"));
// Database uri
const dbURI = process.env.DB_URI;
mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
//test database connection
let db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
console.log("Database connected succefully...");
});
// Set up our main routes
app.use("/api/product", productRouter);
app.use("/api/category", categoryRouter);
app.use("/api/users", usersRouter);
app.use("/api/cart", cartRouter);
app.use("/api/wishlist", wishlistRouter);
app.use("/api/address", addressRouter);
app.use("/api/order", orderRouter);
app.use("/api/permissions", permissionsRouter);
// serve static assets if in production (heroku configuration)
if (process.env.NODE_ENV !== "production") require("dotenv").config();
if (process.env.NODE_ENV == "production") {
// set static folder
app.use(express.static(path.join(__dirname, "views", "build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "views", "build", "index.html"));
});
}
// if the request passes all the middleware without a response
app.use((req, res, next) => {
const error = new Error("Not Found");
error.status = 404;
next(error);
});
// for general error handling
app.use((error, req, res, next) => {
res.status(error.status || 500).json({
message: error.response
});
});
// App's connection port
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is connected on port ${PORT}`);
});