-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (45 loc) · 1.69 KB
/
index.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
var connect = require('connect');
var morgan = require('morgan');
var connectRouter = require('connect-route');
var http = require('http');
var garage = require('./lib/garage');
var port = 3000;
garage.setup().then(function () {
var app = connect();
app.use(morgan('[:date[clf]] :method :url :status :response-time ms - :res[content-length]'));
app.use(connectRouter(function (router) {
router.get('/', function (req, res, next) {
res.statusCode = 200;
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ status: garage.status }));
});
router.post('/', function (req, res, next) {
garage.relay().then(function (status) {
res.statusCode = 201;
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ status: garage.status }));
});
});
router.post('/subscribe', function (req, res, next) {
var sendError = function (err) {
if (err) console.error(err);
res.statusCode = 400;
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ status: garage.status, err: err && err.message || 'Callback missing.' }));
};
if (!req.headers['x-callback']) {
return sendError();
}
garage.subscribe(req.headers['x-callback']).then(function () {
res.statusCode = 201;
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ status: garage.status }));
}).catch(sendError);
});
}));
http.createServer(app).listen(port, function () {
console.log('[%s] Starting server on port %d', (new Date()).toISOString(), port);
});
}).catch(function (err) {
console.error(err);
});