forked from GoogleCloudPlatform/google-cloud-node-todos
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
73 lines (60 loc) · 1.83 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
'use strict';
var bodyParser = require('body-parser');
var express = require('express');
var fs = require('fs');
var markdown = require('markdown').markdown;
var css = require.resolve('./node_modules/github-markdown-css/github-markdown.css');
var apib = require.resolve('./todos.apib');
var githubMarkdownCSS = fs.readFileSync(css).toString();
var todosAPIBlueprint = fs.readFileSync(apib).toString();
var todos = require('./todos.js');
var app = module.exports = express();
app.use(bodyParser.json());
app.get('/_ah/health', function(req, res) {
res.status(200)
.set('Content-Type', 'text/plain')
.send('ok');
});
app.get('/', function(req, res) {
res.status(200)
.set('Content-Type', 'text/html')
.send([
'<html>',
' <head>',
' <style>' + githubMarkdownCSS + '</style>',
' </head>',
' <body class="markdown-body">' + markdown.toHTML(todosAPIBlueprint) + '</body>',
'</html>'
].join('\n'));
});
app.get('/todos', function(req, res) {
todos.getAll(_handleApiResponse(res));
});
app.get('/todos/:id', function(req, res) {
todos.get(req.param('id'), _handleApiResponse(res));
});
app.post('/todos', function(req, res) {
todos.insert(req.body, _handleApiResponse(res, 201));
});
app.put('/todos/:id', function(req, res) {
todos.update(req.param('id'), req.body, _handleApiResponse(res));
});
app.delete('/todos', function(req, res) {
todos.deleteCompleted(_handleApiResponse(res, 204));
});
app.delete('/todos/:id', function(req, res) {
todos.delete(req.param('id'), _handleApiResponse(res, 204));
});
function _handleApiResponse(res, successStatus) {
return function(err, payload) {
if (err) {
console.error(err);
res.status(err.code).send(err.message);
return;
}
if (successStatus) {
res.status(successStatus);
}
res.json(payload);
};
}