-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
79 lines (70 loc) · 2.47 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
const express = require('express')
const bodyParser = require('body-parser')
const MongoClient = require('mongodb').MongoClient
const app = express()
// Link to database
require("dotenv").config({ path: "./config/.env" })
const connectionString = process.env.DB_STRING
const PORT = process.env.PORT
MongoClient.connect(connectionString, { useUnifiedTopology: true })
.then(client => {
console.log('connected to database')
const db = client.db('star-wars-quotes')
const quotesCollection = db.collection('quotes')
const cursor = db.collection('quotes').find()
// Middlewares
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(express.static('public'))
// ========================
// Routes
// ========================
// Create
app.post('/quotes', (req, res) => {
quotesCollection.insertOne(req.body)
.then(result => {
res.redirect('/')
})
.catch(error => console.error(error))
})
// Read
app.get('/', (req, res) => {
db.collection('quotes').find().toArray()
.then(results => {
res.render('index.ejs', { quotes: results })
})
.catch(error => console.error(error))
})
// Update
app.put('/quotes', (req, res) => {
quotesCollection.findOneAndUpdate(
{ name: 'Yoda' },
{ $set: { name: req.body.name,
quote: req.body.quote } },
{ upsert: true }
)
.then(result => {
res.json('Success')
})
.catch(error => console.error(error))
})
// Delete
app.delete('/quotes', (req, res) => {
quotesCollection.deleteOne(
{ name: req.body.name }
)
.then(result => {
if (result.deletedCount === 0){
return res.json('No quote to delete.')
}
res.json("Deleted Darth Vader's quote.")
})
.catch(error => console.error(error))
})
// Listen
app.listen(process.env.PORT, () => {
console.log(`listening on port ${PORT}`)
})
})
.catch(console.error)