/
index.js
98 lines (82 loc) · 2.26 KB
/
index.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
const dotenv = require('dotenv').config();
const Person = require('./models/person');
const ObjectID = require('mongodb').ObjectID;
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
const cors = require('cors');
app.use(bodyParser.json())
app.use(morgan('tiny'))
app.use(cors());
app.use(express.static('build'))
app.get('/api/persons', function(req, res){
Person.find({})
.then((data) => {res.json(data)})
.catch((err) => {
console.log('Cannot get data:')
next(err)
})
})
app.get('/info', function(req, res, next){
Person.find({}).countDocuments()
.then((data) => {
res.send(
`<p>Phonebook has info for ${data} people</p>
<p>${new Date()}</p>`
)
})
.catch((err) => {
console.log('Cannot get info:', err)
next(err)
})
})
app.get('/api/persons/:id', function(req, res, next){
Person.findById(req.params.id)
.then((data) => {
if (data) res.send(data)
else res.status(404).send("Person not found")
})
.catch((err) => {
console.log('Something went wrong:', err);
next(err);
})
})
app.put('/api/persons/:id', function(req, res, next){
Person.findByIdAndUpdate(req.params.id, req.body, {new: true}, function(err, doc){
if (err) next(err)
if (doc) res.json(doc)
else res.status(400).end('Document has been deleted')
})
})
app.delete('/api/persons/:id', function(req, res, next){
Person.findOneAndDelete({_id: ObjectID(req.params.id)}, (err, result) => {
if (err) {
console.log('Something went wrong:', err)
next(err)
}
res.json(result)
})
})
app.post('/api/persons', function(req, res){
let newPerson = new Person(req.body);
newPerson.save()
.then((data) => res.json(data))
.catch((err)=> {
console.log('Cannot save data:', err)
res.status(400).send('Bad request')
})
})
const unknownRouteHandler = function(req, res, next){
res.end('Unknown Route')
}
const errorhandler = function(err, req, res, next){
console.log('Error: ', err);
res.status(500).end('Something went wrong');
}
app.use(unknownRouteHandler)
app.use(errorhandler)
const port = process.env.PORT || PORT;
app.listen(port, function(){
console.log(`server is running on port ${port}`);
})