-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequestHandlers.js
72 lines (62 loc) · 2.42 KB
/
requestHandlers.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
// modules
var querystring = require('querystring')
, fs = require('fs')
, SPACE = require('./SPACE')
, door = require('./door_status');
// setup SPACE module with options
var spaceOptions = {
staticInfoFile : "./data/maschinenraum.json",
}
, space = SPACE.create(spaceOptions);
// GET / (home)
function home(response) {
console.log("Request handler 'home' was called.");
// build response
var body = 'NODE.JS SpaceAPI SERVER\n=======================\n\n';
body += 'Space: ' + space.get('space') + ' -- ' + space.get('tagline');
body += '\n\nMaybe you want to GET /resource.format';
body += '\n\nResources: [ "status" ]';
body += '\nFormats: [ "json", "txt" ]';
body += '\nExample: /status.json';
body += '\n\nSome static info:\n';
body += JSON.stringify(space.get(), null, 2);
// send response
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(body);
response.end();
console.log("Response sent.");
}
// GET /status (SpaceAPI)
function spaceStatus(response, request, parameters) {
console.log("Request handler 'spaceStatus' was called.");
door.get(space, function(result) {
//console.info("callback");
space.set("open", result.door_open);
space.set("status", result.door_status);
// Set 'lastchange' timestamp to time of tweet
space.set("lastchange", Math.round(result.timestamp.getTime() / 1000));
// Set 'generated_at' timestamp to NOW
space.set("generated_at", Math.round(new Date().getTime() / 1000));
// build the response
// set HTTP headers
response.writeHead(200, {
"Cache-Control": "no-cache",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
});
// distinguish output formats
console.log("Output format: " + parameters.format);
if (parameters.format === ".json") {
// make JSON from data object, send this as response
// signature: JSON.stringify([theData], [aReplacerFunction], [theNumberOfSpaces]OR[aCharacterForIndent])
response.write(JSON.stringify(space.get(), null, null));
} else {
response.write(JSON.stringify(space.get(), null, 2));
}
response.end();
console.log("Response sent");
} );
}
// export public methods
exports.home = home;
exports.spaceStatus = spaceStatus;