-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
80 lines (72 loc) · 1.99 KB
/
app.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
var restify = require('restify');
var cors = require('cors');
var util = require('util');
var config = require('./config.json');
var svitchManager = require('./svitch-manager');
var server = restify.createServer({
name: 'orvibo-rest',
version: '0.0.0'
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(cors({
origin: function(origin, callback) {
var originIsWhitelisted = config.allowedClients.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
}));
/**
* Adds links to a svitch object
* @param {Svitch} The svitch to which links are to be added
* @return {Svitch} The svitch, with links added
*/
var injectLinksIntoSvitch = function(svitch) {
svitch._links = [
{
rel: 'self',
href: util.format('%s://%s:%s/svitches/%s', config.secure ? 'https' : 'http', config.host, config.port, svitch.id)
}
];
return svitch;
};
server.use(function (req, res, next) {
console.log(req.method, req.path());
next();
});
server.get('/', function (req, res) {
svitchManager.getSvitches()
.then(function (svitches) {
svitches = svitches.map(function (svitch) {
return injectLinksIntoSvitch(svitch);
});
res.send(svitches);
});
});
server.get('/svitches/:id', function (req, res, next) {
svitchManager.getById(req.params.id)
.then(function (svitch) {
console.log('sv', svitch);
res.send(injectLinksIntoSvitch(svitch));
}, function (err) {
res.status(404);
next(new Error(err));
});
});
server.put('/svitches/:id', function (req, res, next) {
svitchManager.setSvitchState(req.params.id, req.body.st)
.then(function (output) {
svitchManager.getById(req.params.id)
.then(function (svitch) {
res.send(injectLinksIntoSvitch(svitch));
}, function (err) {
res.status(404);
next(new Error(err));
});
}, function (err) {
next(new Error(err));
});
});
server.listen(config.port, function () {
console.log('%s listening at %s', server.name, server.url);
});