forked from ccano2011/election-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
81 lines (69 loc) · 2.26 KB
/
server.js
File metadata and controls
81 lines (69 loc) · 2.26 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
const express = require('express');
const cors = require('cors')
const bodyParser = require('body-parser');
const logger = require('morgan');
const Schema = require('./models/schema')
// const postsRoutes = require('./routes/posts');
const db = require('./db/connection')
const PORT = process.env.PORT || 3000
const app = express();
app.use(cors())
app.use(bodyParser.json())
app.use(logger('dev'))
// app.use('/api', postsRoutes);
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
app.listen(PORT, () => console.log(`Listening on port: ${PORT}`))
app.get('/', (req, res) => res.send("Elections Back-end Root; Test CRUD in postman with localhost:3000/ballotreq"))
app.get('/ballotreq', async (req, res) => {
try {
const info = await Schema.find()
res.json(info)
} catch (error) {
res.status(500).json({ error: error.message })
}
})
app.get('/ballotreq/:id', async (req, res) => {
try {
const { id } = req.params
const info = await Schema.findById(id)
if (!info) throw Error('Request not found!')
res.json(info)
} catch (e) {
console.log(e)
res.send('Catch error: request not found!')
}
})
app.post('/ballotreq', async (req, res) => {
try {
const info = await new Schema(req.body)
await info.save()
res.status(201).json(info)
} catch (error) {
console.log(error)
res.status(500).json({ error: error.message })
}
})
app.put('/ballotreq/:id', async (req, res) => {
const { id } = req.params
await Schema.findByIdAndUpdate(id, req.body, { new: true }, (error, info) => {
if (error) {
return res.status(500).json({ error: error.message })
}
if (!info) {
return res.status(404).json({ message: 'Info not found!' })
}
res.status(200).json(info)
})
})
app.delete('/ballotreq/:id', async (req, res) => {
try {
const { id } = req.params;
const deleted = await Schema.findByIdAndDelete(id)
if (deleted) {
return res.status(200).send("Request deleted, democracy subverted")
}
throw new Error("Request not found, sorry Putin")
} catch (error) {
res.status(500).json({ error: error.message })
}
})