forked from Technigo/project-happy-thoughts-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
137 lines (122 loc) · 3.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import express from 'express'
import cors from 'cors'
import mongoose from 'mongoose'
import listEndpoints from 'express-list-endpoints'
import dotenv from 'dotenv'
dotenv.config()
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/happyThoughts"
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
mongoose.Promise = Promise
const port = process.env.PORT || 8080
const app = express()
app.use(cors())
app.use(express.json())
const thoughtSchema = new mongoose.Schema({
message: {
type: String,
required: [true, "Please enter a message."],
trim: true,
minlength: [5, 'Oops your message needs to be longer than 5 characters'],
maxlength: [140, 'Oops, message is too long! Max length is 140 characters']
},
hearts: {
type: Number,
default: 0
},
createdAt: {
type: Date,
default: Date.now
},
author: {
type: String,
default: 'Anonymous',
}
})
const Thought = mongoose.model('Thought', thoughtSchema)
app.get('/', (req, res) => {
res.send(listEndpoints(app))
})
// GET Endpoint to return 20 thoughts, sorted by createdAt to show the most recent thoughts first.
app.get('/thoughts', async (req, res) => {
try {
const allThoughts = await Thought.find()
.sort({ createdAt: 'descending' })
.limit(20)
res.status(200).json(allThoughts)
} catch (error) {
res
.status(400)
.json(error)
}
})
// POST a new thought
app.post('/thoughts', async (req, res) => {
try {
const newThought = await new Thought({
message: req.body.message,
author: req.body.author
}).save()
res.status(200).json(newThought)
} catch (error) {
if (error.code === 11000) {
res.status(400).json({ message: 'Duplicated value', fields: error.keyValue })
}
res.status(400).json(error)
}
})
// POST - update like/heart property on on thought object
app.post('/thoughts/:id/like', async (req, res) => {
const { id } = req.params
try {
const updatedThought = await Thought.findByIdAndUpdate(
id,
{ $inc: {
hearts: 1
}
},
{
new: true
},
)
if (updatedThought) {
res.status(200).json(updatedThought)
} else {
res.status(404).json({ message: 'Not found'})
}
} catch (error) {
res.status(400).json({ message: 'Invalid request', error })
}
})
// Delete thought by id
app.delete('/thoughts/:id', async (req, res) => {
const { id } = req.params
try {
const deletedThought = await Thought.findByIdAndDelete(id)
if (deletedThought) {
res.status(200).json(deletedThought)
} else {
res.status(404).json({ message: 'Not found' })
}
} catch (error) {
res.status(400).json({ message: 'Invalid request', error })
}
})
// PUT - update thought object by id
app.put('/thoughts/:id', async (req, res) => {
const {id} = req.params
try {
const updatedThought = await Thought.findOneAndReplace({ _id: id }, req.body, { new: true })
if (updatedThought) {
res.status(200).json(updatedThought)
} else {
res.status(404).json({ message: 'Not found'})
}
} catch(error) {
res.status(400).json({ message: 'Invalid request', error })
}
})
// Start the server
app.listen(port, () => {
// eslint-disable-next-line
console.log(`Server running on http://localhost:${port}`)
})