forked from spaceapegames/FoosLadder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapimap.js
102 lines (90 loc) · 2.31 KB
/
apimap.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
var qs = require('querystring');
var users = require("./api/users.js");
var matches = require("./api/matches.js");
var init = require("./api/init.js");
var customapi = require("./api/customapi.js");
init.init();
exports.afterReady = function(callback) { init.afterReady(callback); }
var map = {
getPlayers:users.getUsers,
addPlayer:users.addUser,
getPlayersByIds:users.getPlayersByIds,
getExpectedScores:users.getExpectedScores,
getRatingChange:users.getRatingChange,
getMatchUps:users.getMatchUps,
getMatches:matches.getMatches,
getMatchesRaw:matches.getMatchesRaw,
addMatch:matches.addMatch,
assignCardId:users.assignCardId,
rebuiltMatchStats:matches.rebuiltMatchStats,
repeatMatchStats:matches.repeatMatchStats,
getRecentGainers:customapi.getRecentGainers
};
exports.runAPI = function(request, response)
{
var OK;
if (request.method == 'POST') {
var bodystring = '';
request.on('data', function (data) {
bodystring += data;
});
request.on('end', function () {
var body = qs.parse(bodystring);
console.log("body: "+JSON.stringify(body));
runAPIBody(body, response);
});
}
else
{
var body = require('url').parse(request.url, true).query;
console.log("body: "+JSON.stringify(body));
runAPIBody(body, response);
}
};
function runAPIBody(body, response)
{
var requestkey = body.request;
//console.log("runAPI: " + requestkey);
var apifunction = map[requestkey];
if(apifunction)
{
try
{
apifunction(body, onApiFunctionCallback);
}
catch (err)
{
console.log("Error:", err);
respondError(response, "Internal error");
}
function onApiFunctionCallback(data)
{
try
{
response.writeHeader(200, {"Content-Type": "text/plain", "Cache-control": "no-cache"});
response.write(JSON.stringify(data));
response.end();
}
catch (err)
{
console.log("Error:", data, err);
respondError(response, "Internal error");
}
}
}
else
{
respondError(response, "undefined request");
}
}
function respondError(response, message)
{
console.log("Erorr with request. "+message);
response.writeHeader(500, {"Content-Type": "text/plain"});
response.write('{"status":"error", "message":"'+message+'"}');
response.end();
}
getFunctionForAPIString = function(apistring)
{
return map[apistring];
};