-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquote.jses
64 lines (53 loc) · 1.85 KB
/
quote.jses
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
var express = require('express');
var app = express();
var quotes = [
{ author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"},
{ author : 'Walt Disney', text : "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"},
{ author : 'Unknown', text : "Even the greatest was once a beginner. Don’t be afraid to take that first step."},
{ author : 'Neale Donald Walsch', text : "You are afraid to die, and you’re afraid to live. What a way to exist."}
];
// make express handle JSON and other requests
app.use(express.bodyParser());
// serve up files from this directory
app.use(express.static(__dirname));
// if not able to serve up a static file try and handle as REST
invocation
app.use(app.router);
app.get('/quote/random', function(req, res) {
var id = Math.floor(Math.random() * quotes.length);
var q = quotes[id];
res.send(q);
});
app.get('/quote/:id', function(req, res) {
if(quotes.length <= req.params.id || req.params.id < 0) {
res.statusCode = 404;
return res.send('Error 404: No quote found');
}
var q = quotes[req.params.id];
res.send(q);
});
app.post('/quote', function(req, res) {
if(!req.body.hasOwnProperty('author') ||
!req.body.hasOwnProperty('text')) {
res.statusCode = 400;
return res.send('Error 400: Post syntax incorrect.');
}
var newQuote = {
author : req.body.author,
text : req.body.text
};
quotes.push(newQuote);
res.send(newQuote);
});
app.delete('/quote/:id', function(req, res) {
if(quotes.length <= req.params.id) {
res.statusCode = 404;
return res.send('Error 404: No quote found');
}
quotes.splice(req.params.id, 1);
res.json(true);
});
// use PORT set as an environment variable
var server = app.listen(process.env.PORT, function() {
console.log('Listening on port %d', server.address().port);
});