-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
92 lines (82 loc) · 2.61 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
90
91
92
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const path = require("path");
//db config
const db = require("./config/keys").mongoURI;
//connect to MongoDB
mongoose
.connect(db, { useNewUrlParser: true, useFindAndModify: false, useUnifiedTopology: true })
.then(() => console.log("MongoDB connected"))
.catch(err => console.log("MongoDB error -> ", err));
const app = express();
const port = require("./config/keys").PORT || 5000;
// Load Model
const Post = require('./models/post.model');
// To get the data from a POST
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post("/api/add", (req, res) => {
let id = req.body.id ? req.body.id : null;
Post.findById(id)
.then(post => {
if (post) {
const postFields = {};
if (req.body.topic) postFields.topic = req.body.topic;
if (req.body.description) postFields.description = req.body.description;
Post.findOneAndUpdate({ _id: id }, { $set: postFields }, { new: true })
.then(result => {
return res.status(201).send({
success: true,
data: result,
message: "Post updated successfully",
type: "success"
})
})
.catch(err => console.log("Post update err -> ", err));
} else {
const newPost = new Post(req.body);
newPost.save()
.then(result => {
res.status(201).send({
success: true,
data: result,
message: "Post created successfully",
type: "success"
});
})
.catch(err => console.log("Create new post error -> ", err))
}
})
.catch(err => console.log("Post add error -> ", err))
})
app.get("/api", (req, res) => {
Post.find({})
.then(result => {
res.status(200).send(result);
})
.catch(err => {
console.log("Create new post error -> ", err)
})
})
app.delete("/api/:post_id", (req, res) => {
Post.findByIdAndDelete(req.params.post_id)
.then(result => {
res.status(200).send({
success: true,
data: result,
message: "Post deleted successfully",
type: "success"
});
})
.catch(err => console.log("Post delete err -> ", err));
});
if (require("./config/keys").NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
app.listen(port, function () {
console.log('App listening on port ' + port);
});