forked from Technigo/project-happy-thoughts-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
83 lines (71 loc) · 1.99 KB
/
server.js
File metadata and controls
83 lines (71 loc) · 1.99 KB
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
import express from "express";
import cors from "cors";
import mongoose from "mongoose";
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/happy-thoughts";
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.Promise = Promise;
// Defines the port the app will run on. Defaults to 8080, but can be overridden
// when starting the server. Example command to overwrite PORT env variable value:
// PORT=9000 npm start
const port = process.env.PORT || 8080;
const app = express();
const Thought = mongoose.model('Thought', {
message: {
type: String,
required: true,
minlength:5,
maxlength:140
},
createdAt: {
type: Date,
default: Date.now
},
hearts: {
type: Number,
default: 0
}
})
// Add middlewares to enable cors and json body parsing
app.use(cors());
app.use(express.json());
// Start defining your routes here
app.get("/", (req, res) => {
res.send("Welcome to Frida's happy vibes API!");
});
app.get('/thoughts', async (req, res) => {
const thoughts = await Thought.find().sort({createdAt: 'desc'}).limit(20).exec()
res.json(thoughts);
})
app.post('/thoughts', async (req, res) => {
const {message} = req.body;
const thought = new Thought({message})
try{
const savedThought = await thought.save();
res.status(201).json(savedThought)
}catch (e) {
res.status(400).json({message: 'Could not save thought to the database', error: e.errors})
}
})
app.post('/thoughts/:thoughtId/like', async (req, res) => {
const { thoughtId } = req.params
try{
const heartsUpdated = await Thought.findByIdAndUpdate(
thoughtId,
{$inc: {hearts: 1}},
{new:true}
);
res.status(200).json({
success: true,
response: `Thought ${heartsUpdated._id} has been updated with a heart`
});
} catch (e) {
res.status(400).json({
success: false,
response: "Thought-Id not found"
});
}
});
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});