-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
115 lines (94 loc) · 2.83 KB
/
server.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
103
104
105
106
107
108
109
110
111
112
113
114
115
var fs = require('fs');
var Hapi = require('hapi');
var HapiJsonView = require('hapi-json-view');
var Good = require('good');
var Path = require('path');
var _ = require('underscore');
var Query = require('datapackage-query');
// Create Server
var server = new Hapi.Server();
server.connection({
address: '127.0.0.1',
port: 8888,
routes: {
cors: true,
jsonp: 'callback'
}
});
server.views({
engines: {
json: {
module: HapiJsonView.create(),
compileMode: 'async',
contentType: 'application/json',
}
}
})
// API Config
var config = JSON.parse(fs.readFileSync('./api.json', 'utf8'));
console.log('Loaded API config for: ' + config.name);
// JSON Api
server.route({
method: 'GET',
path: '/{dataset*}',
handler: function(request, reply) {
// If no param, show ToC
if (!request.params.dataset) {
var package_path = config.paths.data + config.prefix + config.index;
var data_path = Path.dirname(package_path + '/datapackage.json');
console.log('Open: ' + package_path + '/datapackage.json');
Query.Grow(package_path + '/datapackage.json', function(schema) {
// Open CSV Data
Query.Twirl(data_path, schema.resources[0], request.url.query, function(csv_to_json_data) {
var response = _.omit(schema, 'resources');
response['status'] = 'success';
response['result'] = csv_to_json_data;
// Render
reply(response);
});
});
}
else if (_.indexOf(config.datasets, request.params.dataset) > -1) {
var package_path = config.paths.data + config.prefix + request.params.dataset;
var data_path = Path.dirname(package_path + '/datapackage.json');
console.log('Open: ' + package_path + '/datapackage.json');
Query.Grow(package_path + '/datapackage.json', function(schema) {
// If Schema Contains Multiple
_.each(schema.resources, function(resource, key) {
// Open CSV Data
Query.Twirl(data_path, resource, request.url.query, function(csv_to_json_data) {
var response = _.omit(schema, 'resources');
response['status'] = 'success';
response['result'] = csv_to_json_data;
// Render
reply(response);
});
});
});
} else {
// Show Error
reply({
status: 'error',
name: 'Shucks there is no dataset called [' + request.params.dataset + ']'
});
}
}
});
// Good Logging
server.register({
register: Good,
options: {
reporters: [{
reporter: require('good-console'),
args:[{ log: '*', response: '*' }]
}]
}
}, function (err) {
if (err) {
throw err; // something bad happened loading the plugin
}
// Start
server.start(function () {
server.log('info', 'Server running at: ' + server.info.uri);
});
});