index.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. const express = require('express');
  2. const helpers = require('./helpers.js');
  3. const nutsData = require('./nuts-data.js');
  4. const cors = require('cors');
  5. const R = require('r-script');
  6. var where = require('lodash.where');
  7. const app = express();
  8. const _datasetsFilePath = 'data/datasets.csv';
  9. const _dataFilePath = 'data/data.csv';
  10. //const _clusteringInputFilePath = 'data/clustering/input_all.csv';
  11. const _clusteringModifiedFilePath = 'data/clustering/input_modified.csv';
  12. const _clustersFilePath = 'data/clustering/out_file.csv';
  13. var _datasets = undefined;
  14. var _ruralData = undefined;
  15. // parse incoming POST requests body to JSON
  16. app.use(express.json());
  17. // handle CORS
  18. app.use(cors())
  19. // serve static files from the /static directory
  20. app.use(express.static('static'))
  21. // set PUG as default rendering engine
  22. app.set('view engine', 'pug')
  23. /* Dummy web service call without the method specified */
  24. app.get('/', (req, res) => {
  25. res.send('Rural attractivness web service');
  26. });
  27. /* Makes refresh of the data loaded to the server objects.
  28. Must be called after the CSV data has changed */
  29. app.get('/refresh', (req, res, next) => {
  30. nutsData.loadDatasets(_datasetsFilePath, function (ds) {
  31. //console.log('Datasets loaded succesfully');
  32. _datasets = ds;
  33. nutsData.loadRuralData(_dataFilePath, _datasets, function (rd) {
  34. //console.log('Rural data loaded succesfully');
  35. _ruralData = rd;
  36. res.send('Data refreshed');
  37. });
  38. });
  39. });
  40. /* Returns JSON array with the list of all the datasets */
  41. app.get('/datasets', (req, res, next) => {
  42. if (_datasets) {
  43. helpers.formatResponse(_datasets, req, res);
  44. }
  45. else {
  46. nutsData.loadDatasets(_datasetsFilePath, function (ds) {
  47. //console.log('Datasets loaded callback');
  48. _datasets = ds;
  49. helpers.formatResponse(_datasets, req, res);
  50. });
  51. }
  52. });
  53. /* Returns attractivity data for the region with ID equal to the 'nuts' parameter */
  54. app.get('/scores/:nuts', (req, res, next) => {
  55. if (_ruralData) {
  56. returnRegionScores(req.params.nuts, req, res);
  57. }
  58. else {
  59. if (_datasets) { // datasets must be loaded prior to data loading
  60. nutsData.loadRuralData(_dataFilePath, _datasets, function (rd) {
  61. _ruralData = rd;
  62. returnRegionScores(req.params.nuts, req, res);
  63. });
  64. }
  65. else {
  66. nutsData.loadDatasets(_datasetsFilePath, function (ds) {
  67. _datasets = ds;
  68. nutsData.loadRuralData(_dataFilePath, _datasets, function (rd) {
  69. _ruralData = rd;
  70. returnRegionScores(req.params.nuts, req, res);
  71. });
  72. });
  73. }
  74. }
  75. });
  76. /* Returns attractivity data for all the regions in source CSV data. */
  77. app.get('/scores', (req, res, next) => {
  78. if (_ruralData)
  79. helpers.formatResponse(_ruralData, req, res);
  80. else {
  81. if (_datasets) { // datasets must be loaded prior to data loading
  82. nutsData.loadRuralData(_dataFilePath, _datasets, function (rd) {
  83. _ruralData = rd;
  84. helpers.formatResponse(_ruralData, req, res);
  85. });
  86. }
  87. else {
  88. nutsData.loadDatasets(_datasetsFilePath, function (ds) {
  89. _datasets = ds;
  90. nutsData.loadRuralData(_dataFilePath, _datasets, function (rd) {
  91. _ruralData = rd;
  92. helpers.formatResponse(_ruralData, req, res);
  93. });
  94. });
  95. }
  96. }
  97. });
  98. /* Computes and returns attractivity data for all the NUTS regions based on the
  99. incomming datasets and factor weights. */
  100. app.post('/scores', (req, res, next) => {
  101. //console.log("query: " + JSON.stringify(req.body.factors, null, 4));
  102. if (_ruralData) {
  103. returnAllScores(req, res);
  104. }
  105. else {
  106. if (_datasets) { // datasets must be loaded prior to data loading
  107. nutsData.loadRuralData(_dataFilePath, _datasets, function (rd) {
  108. _ruralData = rd;
  109. returnAllScores(req, res);
  110. });
  111. }
  112. else {
  113. nutsData.loadDatasets(_datasetsFilePath, function (ds) {
  114. _datasets = ds;
  115. nutsData.loadRuralData(_dataFilePath, _datasets, function (rd) {
  116. _ruralData = rd;
  117. returnAllScores(req, res);
  118. });
  119. });
  120. }
  121. }
  122. });
  123. /*
  124. Only testing purposes
  125. */
  126. app.get('/runR', (req, res, next) => {
  127. //console.log(console);
  128. console.log('calling R...')
  129. //console.log(req)
  130. R('./r/selected_data.r').call(
  131. function (err, data) {
  132. console.log('R done');
  133. if (err) {
  134. console.log(err.toString('utf8'));
  135. data = { result: err.toString('utf8') };
  136. }
  137. else {
  138. console.log(data);
  139. data = { result: 'R call succesful' };
  140. }
  141. helpers.formatResponse({ response: data }, req, res);
  142. }
  143. );
  144. });
  145. /*
  146. Just informative response. POST with JSON data is required.
  147. */
  148. app.get('/clusters', (req, res, next) => {
  149. const data = { response: '/clusters method is only available under POST' }
  150. helpers.formatResponse(data, req, res);
  151. });
  152. /*
  153. Modifies input CSV file, calls R script, loads the resulting CSV file and returns it
  154. */
  155. app.post('/clusters', async (req, res, next) => {
  156. try {
  157. if (!_datasets) {
  158. //TODO: promisify all functions to avoid callback hell and make this work properly
  159. await nutsData.loadDatasets(_datasetsFilePath, function (ds) {
  160. //console.log('Datasets loaded succesfully');
  161. _datasets = ds;
  162. })
  163. }
  164. //console.log(req.body);
  165. const clusteringData = await nutsData.loadClusteringInput(
  166. _dataFilePath
  167. );
  168. await nutsData.modifyClusteringData({
  169. datasets: _datasets,
  170. data: clusteringData,
  171. params: req.body,
  172. outputFileName: _clusteringModifiedFilePath
  173. });
  174. handleRCall(req, res);
  175. } catch (error) { // Catch errors in async functions
  176. next(error.toString());
  177. }
  178. });
  179. app.get('/georeport/:nuts', (req, res, next) => {
  180. if (_ruralData) {
  181. renderPugReport(req.params.nuts, req, res);
  182. }
  183. else {
  184. if (_datasets) { // datasets must be loaded prior to data loading
  185. nutsData.loadRuralData(_dataFilePath, _datasets, function (rd) {
  186. _ruralData = rd;
  187. renderPugReport(req.params.nuts, req, res);
  188. });
  189. }
  190. else {
  191. nutsData.loadDatasets(_datasetsFilePath, function (ds) {
  192. _datasets = ds;
  193. nutsData.loadRuralData(_dataFilePath, _datasets, function (rd) {
  194. _ruralData = rd;
  195. renderPugReport(req.params.nuts, req, res);
  196. });
  197. });
  198. }
  199. }
  200. });
  201. // start the service on the port xxxx
  202. app.listen(3000, () => console.log('Rural attractivity WS listening on port 3000...'));
  203. function renderPugReport(nuts, req, res) {
  204. var found = false;
  205. _ruralData.forEach(region => {
  206. if (region.nuts == nuts) {
  207. let nutsGeoJson = helpers.loadJSON('static/NUTS3_4326.json');
  208. let filterednutsGeoJson = where(nutsGeoJson.features, { "properties": { "NUTS_ID": nuts } });
  209. let pilots = helpers.loadJSON('static/pilots.json');
  210. region.metadata = {
  211. name: filterednutsGeoJson[0].properties.NUTS_NAME,
  212. code: nuts,
  213. centroid: helpers.getCentroid(filterednutsGeoJson[0].geometry),
  214. pilot: helpers.getPilotRegion(nuts, pilots)
  215. };
  216. res.render('nuts', { region: region, datasets: _datasets });
  217. found = true;
  218. }
  219. });
  220. if (!found)
  221. res.render('err', {});
  222. }
  223. function returnAllScores(req, res) {
  224. var resData = [];
  225. _ruralData.forEach(region => {
  226. //var region = _ruralData[0];
  227. var sumWeight = 0;
  228. var sumValue = 0;
  229. let regionIndexes = { code: region.nuts };
  230. req.body.factors.forEach(f => {
  231. let fi = nutsData.getFactorIndex(region, f);
  232. //console.log("f: " + JSON.stringify(f));
  233. //console.log("fi: " + JSON.stringify(fi));
  234. regionIndexes[f.factor] = fi.index;
  235. sumValue += fi.sumValue * f.weight;
  236. sumWeight += fi.sumWeight;
  237. });
  238. regionIndexes.aggregate = sumValue / sumWeight;
  239. resData.push(regionIndexes);
  240. });
  241. helpers.formatResponse(resData, req, res);
  242. }
  243. function returnRegionScores(nuts, req, res) {
  244. var found = false;
  245. res.header("Content-Type", 'application/json');
  246. _ruralData.forEach(region => {
  247. if (region.nuts == nuts) {
  248. helpers.formatResponse(region, req, res);
  249. found = true;
  250. }
  251. });
  252. if (!found)
  253. // NUTS region not found
  254. res.status(404).send('NUTS region not found.');
  255. }
  256. function handleRCall(req, res) {
  257. console.log('calling R...')
  258. R('./r/selected_data.r').call(
  259. function (err, data) {
  260. console.log('R done');
  261. if (err) {
  262. console.log(err.toString('utf8'));
  263. data = { result: err.toString('utf8') };
  264. res.status(204).send({ response: data });
  265. }
  266. else {
  267. //console.log(data);
  268. nutsData.loadClusters(_clustersFilePath, function (clusterData) {
  269. data = clusterData;
  270. helpers.formatResponse({ response: data }, req, res);
  271. });
  272. }
  273. }
  274. );
  275. }