-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
96 lines (90 loc) · 2.63 KB
/
app.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
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }))
mongoose.connect('mongodb://localhost:27017/wikiDB', { useNewUrlParser: true, useUnifiedTopology: true })
const articleSchema = {
title: {
type: String,
required: [true]
},
content: {
type: String,
required: [true]
}
}
const Article = mongoose.model('Article', articleSchema)
const port = 3000
app.listen(port, () => console.log(`Server listening on port ${port}.`))
app.route('/articles')
.get(async (req, res) => {
try {
const foundArticles = await Article.find()
res.send(foundArticles)
} catch (err) {
res.send(err)
}
})
.post(async (req, res) => {
const { title, content } = req.body
const newArticle = new Article({ title, content })
try {
await newArticle.save()
res.send('Article received and added to the database!')
} catch (err) {
res.send(err)
}
})
.delete(async (req, res) => {
try {
await Article.deleteMany()
res.send('All articles deleted!')
} catch (err) {
res.send(err)
}
})
app.route('/articles/:articleTitle')
.get(async (req, res) => {
try {
const foundArticle = await Article.findOne(
{ title: req.params.articleTitle }
)
if (foundArticle) {
res.send(foundArticle)
} else {
res.send(`Sorry, no article matching the title "${req.params.articleTitle}" was found.`)
}
} catch (err) {
res.send(err)
}
})
.put(async (req, res) => {
const { title, content } = req.body
try {
await Article.replaceOne({ title: req.params.articleTitle },
{ title, content }
)
res.send('Article updated in the database!')
} catch (err) {
res.send(err)
}
})
.patch(async (req, res) => {
try {
await Article.updateOne({ title: req.params.articleTitle },
{ $set: req.body }
)
res.send('Article updated in the database!')
} catch (err) {
res.send(err)
}
})
.delete(async (req, res) => {
try {
await Article.deleteOne({ title: req.params.articleTitle })
res.send('Article deleted!')
} catch (err) {
res.send(err)
}
})