-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
83 lines (69 loc) · 1.93 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
80
81
82
83
// Todo Model //////////////////////////////////////////////////////////////////
const Todo = require('./datastore');
// Configure Express ///////////////////////////////////////////////////////////
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, './public')));
// RESTful Routes for CRUD operations //////////////////////////////////////////
// Create (Crud) -- collection route
app.post('/todo', (req, res) => {
Todo.create(req.body.todoText, (err, newTodo) => {
if (err) {
res.sendStatus(400);
} else {
res.status(201).json(newTodo);
}
});
});
// Read all (cRud) -- collection route
app.get('/todo', (req, res) => {
Todo.readAll((err, todos) => {
if (err) {
res.sendStatus(400);
} else {
res.status(200).json(todos);
}
});
});
// Read one (cRud) -- member route
app.get('/todo/:id', (req, res) => {
Todo.readOne(req.params.id, (err, todo) => {
if (todo) {
res.status(200).json(todo);
} else {
res.sendStatus(404);
}
});
});
// Update (crUd) -- member route
app.put('/todo/:id', (req, res) => {
Todo.update(req.params.id, req.body.todoText, (err, todo) => {
if (todo) {
res.status(200).json(todo);
} else {
res.sendStatus(404);
}
});
});
// Delete (cruD) -- member route
app.delete('/todo/:id', (req, res) => {
Todo.delete(req.params.id, (err) => {
if (err) {
res.sendStatus(404);
} else {
res.sendStatus(204);
}
});
});
// Start & Initialize Web Server ///////////////////////////////////////////////
const port = 3000;
app.listen(port, () => {
console.log('CRUDdy Todo server is running in the terminal');
console.log(`To get started, visit: http://localhost:${port}`);
});
Todo.initialize();