geospatial.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*!
  2. * Module requirements.
  3. */
  4. 'use strict';
  5. const castArraysOfNumbers = require('./helpers').castArraysOfNumbers;
  6. const castToNumber = require('./helpers').castToNumber;
  7. /*!
  8. * ignore
  9. */
  10. exports.cast$geoIntersects = cast$geoIntersects;
  11. exports.cast$near = cast$near;
  12. exports.cast$within = cast$within;
  13. function cast$near(val) {
  14. const SchemaArray = require('../array');
  15. if (Array.isArray(val)) {
  16. castArraysOfNumbers(val, this);
  17. return val;
  18. }
  19. _castMinMaxDistance(this, val);
  20. if (val && val.$geometry) {
  21. return cast$geometry(val, this);
  22. }
  23. return SchemaArray.prototype.castForQuery.call(this, val);
  24. }
  25. function cast$geometry(val, self) {
  26. switch (val.$geometry.type) {
  27. case 'Polygon':
  28. case 'LineString':
  29. case 'Point':
  30. castArraysOfNumbers(val.$geometry.coordinates, self);
  31. break;
  32. default:
  33. // ignore unknowns
  34. break;
  35. }
  36. _castMinMaxDistance(self, val);
  37. return val;
  38. }
  39. function cast$within(val) {
  40. _castMinMaxDistance(this, val);
  41. if (val.$box || val.$polygon) {
  42. const type = val.$box ? '$box' : '$polygon';
  43. val[type].forEach(arr => {
  44. if (!Array.isArray(arr)) {
  45. const msg = 'Invalid $within $box argument. '
  46. + 'Expected an array, received ' + arr;
  47. throw new TypeError(msg);
  48. }
  49. arr.forEach((v, i) => {
  50. arr[i] = castToNumber.call(this, v);
  51. });
  52. });
  53. } else if (val.$center || val.$centerSphere) {
  54. const type = val.$center ? '$center' : '$centerSphere';
  55. val[type].forEach((item, i) => {
  56. if (Array.isArray(item)) {
  57. item.forEach((v, j) => {
  58. item[j] = castToNumber.call(this, v);
  59. });
  60. } else {
  61. val[type][i] = castToNumber.call(this, item);
  62. }
  63. });
  64. } else if (val.$geometry) {
  65. cast$geometry(val, this);
  66. }
  67. return val;
  68. }
  69. function cast$geoIntersects(val) {
  70. const geo = val.$geometry;
  71. if (!geo) {
  72. return;
  73. }
  74. cast$geometry(val, this);
  75. return val;
  76. }
  77. function _castMinMaxDistance(self, val) {
  78. if (val.$maxDistance) {
  79. val.$maxDistance = castToNumber.call(self, val.$maxDistance);
  80. }
  81. if (val.$minDistance) {
  82. val.$minDistance = castToNumber.call(self, val.$minDistance);
  83. }
  84. }