Guest User

Untitled

a guest
Sep 24th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. 'use strict';
  2.  
  3. const {Unit} = require('../../../models/units');
  4. const {BadRequest} = require('../../_shared/errors');
  5. // ----------------------------------------------------------------------------
  6. /**
  7. * @param {*} req
  8. * @return {promise}
  9. */
  10. async function getContextFields(req) {
  11. if (!req.query.displayType) throw new BadRequest('displayType');
  12.  
  13. let aggregate = buildAggregateQuery(req);
  14.  
  15. const aggregateResult = await Unit.aggregate(aggregate).exec();
  16.  
  17. if (aggregateResult[0].measurements.length === 0) throw new BadRequest('displayType');
  18. if (aggregateResult[0].influxTables.length === 0) throw new BadRequest('displayType');
  19.  
  20. let tableSet = new Set(aggregateResult[0].influxTables);
  21. aggregateResult[0].influxTables = [...tableSet];
  22.  
  23. return aggregateResult[0];
  24. }
  25.  
  26.  
  27. /**
  28. * @param {*} req
  29. * @return {*}
  30. */
  31. function buildAggregateQuery(req) {
  32. const match = buildMatch(req);
  33. const filterProject = buildFilterProject(req);
  34. const formatProject = buildFormatProject();
  35. return [match, filterProject, formatProject];
  36. }
  37.  
  38.  
  39. /**
  40. * @param {*} req
  41. * @return {Object}
  42. */
  43. function buildMatch(req) {
  44. return {$match: {'_id': req.unit._id}};
  45. }
  46.  
  47.  
  48. /**
  49. * @param {*} req
  50. * @return {Object}
  51. */
  52. function buildFilterProject(req) {
  53. const displayType = req.query.displayType;
  54. let filterProject = {
  55. $project: {
  56. measurements: {
  57. $filter: {
  58. input: '$measurements',
  59. as: 'measurements',
  60. cond: {$and: [{$eq: [`$$measurements.displayTypes.${displayType}`, true]}]},
  61. },
  62. },
  63. _id: false,
  64. },
  65. };
  66.  
  67. // Find a better way to do that (like with array as query parameter)
  68. let queryFields = [];
  69. if (req.query.field1) queryFields.push(req.query.field1);
  70. if (req.query.field2) queryFields.push(req.query.field2);
  71. if (req.query.field3) queryFields.push(req.query.field3);
  72. if (req.query.field4) queryFields.push(req.query.field4);
  73.  
  74. if (queryFields.length > 0) {
  75. const condition = {$in: [`$$measurements.name`, queryFields]};
  76. filterProject.$project.measurements.$filter.cond.$and.push(condition);
  77. }
  78.  
  79. return filterProject;
  80. }
  81.  
  82. /**
  83. * @return {Object}
  84. */
  85. function buildFormatProject() {
  86. const formatProject = {
  87. $project: {
  88. measurements: '$measurements',
  89. influxTables: '$measurements.influxTable',
  90. },
  91. };
  92.  
  93. return formatProject;
  94. }
  95.  
  96. module.exports = {getContextFields};
Add Comment
Please, Sign In to add comment