forked from Camaromelt/CrudTheHardParts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
77 lines (65 loc) · 1.78 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
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
const Todo = require('./models/todo');
const url = 'mongodb:https://ben:[email protected]:19826/junior-assessment';
// app config
const app = express();
const PORT = 3000;
app.use('/public', express.static(path.join(__dirname, 'public')));
// body parser
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// db connection
mongoose.connect(url, () => {
console.log('You are connected to the DB...');
});
// home
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
// add todo
app.post('/todo', (req, res) => {
const newTodo = req.body;
Todo.create(newTodo, (err, newlyCreated) => {
if (err) {
console.log(err, '<--- error from add todo');
res.status(500).json(err);
} else {
res.json(newlyCreated);
}
});
});
// get all todos
app.get('/todo', (req, res) => {
Todo.find({}, (err, allTodos) => {
if (err) res.status(500).json(err);
res.json(allTodos);
});
});
// delete a todo
app.delete('/todo/:id', (req, res) => {
const deleted = { _id: req.params.id };
Todo.findByIdAndRemove(deleted, (err, response) => {
if (err) res.status(500).json(err);
res.json(response);
});
});
// update one todo
app.patch('/todo/:id', (req, res) => {
const update = {
todo: req.body.todo,
date: Date.now(),
};
Todo.findByIdAndUpdate({ _id: req.params.id }, update, (err, response) => {
if (err) {
res.status(500).json(err);
} else {
res.json(response);
}
});
});
app.listen(PORT, () => console.log(`I am running on ${PORT} ........💩`));