forked from erwintoni/gb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_ajax.js
75 lines (70 loc) · 2.16 KB
/
app_ajax.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
var querystring = require('querystring');
var MAX_BODY = 1024;
// Extract a data object from the request message.
// cb = function(data) where data is Error or Object
exports.parse = function(req, cb) {
var dataString;
req.setEncoding('utf8');
req.on('data', function (chunk) {
if (dataString === undefined) {
dataString = chunk;
} else {
dataString += chunk;
}
if (dataString.length > MAX_BODY) {
return cb(new Error('app_ajax.parse: dataString exceeds ' + MAX_BODY));
}
});
req.on('end', function() {
if (dataString === undefined || dataString.length === 0) return cb({});
try {
var data = JSON.parse(dataString);
if (data) {
cb(data);
} else {
cb(new Error('\napp_ajax.parse: data is false from message body = ' + dataString));
}
} catch (err) {
err.message += '\napp_ajax.parse: ' + err.message + ' for message body = ' + dataString;
return cb(err);
}
});
};
// Send the client data as a JSON string.
exports.data = function(res, data) {
if (data === undefined) {
data = {};
}
var buf = new Buffer(JSON.stringify({'data' : data}), 'utf8');
res.writeHead(200, {
'Content-Type': 'application/json; charset=UTF-8',
'Content-Length': buf.length,
'Pragma': 'no-cache',
'Cache-Control': 'no-cache, no-store'
});
res.end(buf);
};
// Send the client an object with an error property set to 'unspecified error'.
exports.error = function(res, error) {
if (error === undefined) error = new Error('unspecified error');
var buf = new Buffer(JSON.stringify({'error': error.message}), 'utf8');
res.writeHead(200, {
'Content-Type': 'application/json; charset=UTF-8',
'Content-Length': buf.length,
'Pragma': 'no-cache',
'Cache-Control': 'no-cache, no-store'
});
res.end(buf);
};
// Tell client to login.
exports.login = function(res) {
//exports.reply(res, { login: true });
var buf = new Buffer(JSON.stringify({'login' : true}), 'utf8');
res.writeHead(200, {
'Content-Type': 'application/json; charset=UTF-8',
'Content-Length': buf.length,
'Pragma': 'no-cache',
'Cache-Control': 'no-cache, no-store'
});
res.end(buf);
};