-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
97 lines (75 loc) · 2.18 KB
/
Copy pathapp.js
File metadata and controls
97 lines (75 loc) · 2.18 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var books = [
{
id: 1,
title: "Developing Backbone.js Applications",
author: "Addy Osmani"
},
{
id: 2,
title: "JavaScript: The Definitive Guide, 5th Edition",
author: "David Flanagan"
}
];
var nextId = 3;
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(function (req, res, next) {
if(req.url.indexOf("/api") === 0 ||
req.url.indexOf("/bower-components") === 0 ||
req.url.indexOf("/scripts") === 0) {
return next();
}
res.sendFile(__dirname + '/public/index.html');
});
app.get('/api/books', function(req, res) {
res.json(books);
});
app.get('/api/books/:id', function(req, res) {
var book = books.filter(function(book) { return book.id == req.params.id; })[0];
if(!book) {
res.statusCode = 404;
return res.json({ msg: "Book does not exist" });
}
res.json(book);
});
app.post('/api/books', function(req, res) {
if(!req.body.author || !req.body.title) {
res.statusCode = 400;
return res.json({ msg: "Invalid params sent" });
}
var newBook = {
author : req.body.author,
title : req.body.title,
id: nextId++
};
books.push(newBook);
res.json(newBook);
});
app.put('/api/books/:id', function(req, res) {
if(!req.body.author || !req.body.title) {
res.statusCode = 400;
return res.json({ msg: "Invalid params sent" });
}
var book = books.filter(function(book) { return book.id == req.params.id; })[0];
if(!book) {
res.statusCode = 404;
return res.json({ msg: "Book does not exist" });
}
book.author = req.body.author;
book.title = req.body.title;
res.json(book);
});
app.delete('/api/books/:id', function(req, res) {
var book = books.filter(function(book) { return book.id == req.params.id; })[0];
if(!book) {
res.statusCode = 404;
return res.json({ msg: "Book does not exist" });
}
books.splice(books.indexOf(book), 1);
res.statusCode = 204;
res.send({});
});
app.listen(8000);