index.js 7.8 KB

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