forked from dojo/dojo1-dgrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest-node.js
68 lines (59 loc) · 2.07 KB
/
rest-node.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
/*
A simple test server that returns dynamic data.
Sort: not supported
Paging: supports both "limit(count,start)" in the querystring and Range/X-Range header: items=start-end
Hierarchical data: supports the "parent" parameter in the querystring
See: https://github.com/SitePen/dstore/blob/master/docs/Stores.md#request
Launch command: node rest-node.js
Stop server with Ctrl+C
*/
var http = require('http');
var process = require('process');
var url = require('url');
var restHelpers = require('./restHelpers');
var PORT_NUMBER = 8040;
var RESPONSE_DELAY_MIN = 20;
var RESPONSE_DELAY_MAX = 100;
var server = http.createServer(function (request, response) {
var requestUrl = new url.URL(request.url, 'http://' + request.headers.host);
var searchParams = {};
requestUrl.searchParams.forEach(function (value, name) {
searchParams[name] = value;
});
var responseData = restHelpers.getResponseData(searchParams, request.headers);
var responseDelay = restHelpers.getDelay(RESPONSE_DELAY_MIN, RESPONSE_DELAY_MAX);
var responseJson = JSON.stringify(responseData.items);
response.setHeader('Access-Control-Allow-Headers', '*, Range, X-Range, X-Requested-With');
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Expose-Headers', 'Content-Range');
response.setHeader('Content-Length', Buffer.byteLength(responseJson));
response.setHeader('Content-Type', 'application/json');
response.setHeader('Content-Range', responseData.contentRange);
response.write(responseJson);
if (responseDelay) {
setTimeout(function () {
response.end();
}, responseDelay);
}
else {
response.end();
}
});
server.listen(PORT_NUMBER);
console.log('server listening on port ' + PORT_NUMBER + '...');
if (process.platform === 'win32') {
var readline = require('readline');
var readlineInterface = readline.createInterface({
input: process.stdin,
output: process.stdout
});
readlineInterface.on('SIGINT', function () {
process.emit('SIGINT');
});
}
process.on('SIGINT', function () {
server.close(function () {
console.log('server stopped');
process.exit();
});
});