OfflineQuery.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. "use strict";
  2. /* eslint-disable no-loop-func */
  3. const equalObjects = require('./equals').default;
  4. const decode = require('./decode').default;
  5. const ParseError = require('./ParseError').default;
  6. const ParsePolygon = require('./ParsePolygon').default;
  7. const ParseGeoPoint = require('./ParseGeoPoint').default;
  8. /**
  9. * contains -- Determines if an object is contained in a list with special handling for Parse pointers.
  10. *
  11. * @param haystack
  12. * @param needle
  13. * @private
  14. * @returns {boolean}
  15. */
  16. function contains(haystack, needle) {
  17. if (needle && needle.__type && (needle.__type === 'Pointer' || needle.__type === 'Object')) {
  18. for (const i in haystack) {
  19. const ptr = haystack[i];
  20. if (typeof ptr === 'string' && ptr === needle.objectId) {
  21. return true;
  22. }
  23. if (ptr.className === needle.className && ptr.objectId === needle.objectId) {
  24. return true;
  25. }
  26. }
  27. return false;
  28. }
  29. return haystack.indexOf(needle) > -1;
  30. }
  31. function transformObject(object) {
  32. if (object._toFullJSON) {
  33. return object._toFullJSON();
  34. }
  35. return object;
  36. }
  37. /**
  38. * matchesQuery -- Determines if an object would be returned by a Parse Query
  39. * It's a lightweight, where-clause only implementation of a full query engine.
  40. * Since we find queries that match objects, rather than objects that match
  41. * queries, we can avoid building a full-blown query tool.
  42. *
  43. * @param className
  44. * @param object
  45. * @param objects
  46. * @param query
  47. * @private
  48. * @returns {boolean}
  49. */
  50. function matchesQuery(className, object, objects, query) {
  51. if (object.className !== className) {
  52. return false;
  53. }
  54. let obj = object;
  55. let q = query;
  56. if (object.toJSON) {
  57. obj = object.toJSON();
  58. }
  59. if (query.toJSON) {
  60. q = query.toJSON().where;
  61. }
  62. obj.className = className;
  63. for (const field in q) {
  64. if (!matchesKeyConstraints(className, obj, objects, field, q[field])) {
  65. return false;
  66. }
  67. }
  68. return true;
  69. }
  70. function equalObjectsGeneric(obj, compareTo, eqlFn) {
  71. if (Array.isArray(obj)) {
  72. for (let i = 0; i < obj.length; i++) {
  73. if (eqlFn(obj[i], compareTo)) {
  74. return true;
  75. }
  76. }
  77. return false;
  78. }
  79. return eqlFn(obj, compareTo);
  80. }
  81. /**
  82. * Determines whether an object matches a single key's constraints
  83. *
  84. * @param className
  85. * @param object
  86. * @param objects
  87. * @param key
  88. * @param constraints
  89. * @private
  90. * @returns {boolean}
  91. */
  92. function matchesKeyConstraints(className, object, objects, key, constraints) {
  93. if (constraints === null) {
  94. return false;
  95. }
  96. if (key.indexOf('.') >= 0) {
  97. // Key references a subobject
  98. const keyComponents = key.split('.');
  99. const subObjectKey = keyComponents[0];
  100. const keyRemainder = keyComponents.slice(1).join('.');
  101. return matchesKeyConstraints(className, object[subObjectKey] || {}, objects, keyRemainder, constraints);
  102. }
  103. let i;
  104. if (key === '$or') {
  105. for (i = 0; i < constraints.length; i++) {
  106. if (matchesQuery(className, object, objects, constraints[i])) {
  107. return true;
  108. }
  109. }
  110. return false;
  111. }
  112. if (key === '$and') {
  113. for (i = 0; i < constraints.length; i++) {
  114. if (!matchesQuery(className, object, objects, constraints[i])) {
  115. return false;
  116. }
  117. }
  118. return true;
  119. }
  120. if (key === '$nor') {
  121. for (i = 0; i < constraints.length; i++) {
  122. if (matchesQuery(className, object, objects, constraints[i])) {
  123. return false;
  124. }
  125. }
  126. return true;
  127. }
  128. if (key === '$relatedTo') {
  129. // Bail! We can't handle relational queries locally
  130. return false;
  131. }
  132. if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(key)) {
  133. throw new ParseError(ParseError.INVALID_KEY_NAME, `Invalid Key: ${key}`);
  134. } // Equality (or Array contains) cases
  135. if (typeof constraints !== 'object') {
  136. if (Array.isArray(object[key])) {
  137. return object[key].indexOf(constraints) > -1;
  138. }
  139. return object[key] === constraints;
  140. }
  141. let compareTo;
  142. if (constraints.__type) {
  143. if (constraints.__type === 'Pointer') {
  144. return equalObjectsGeneric(object[key], constraints, (obj, ptr) => {
  145. return typeof obj !== 'undefined' && ptr.className === obj.className && ptr.objectId === obj.objectId;
  146. });
  147. }
  148. return equalObjectsGeneric(decode(object[key]), decode(constraints), equalObjects);
  149. } // More complex cases
  150. for (const condition in constraints) {
  151. compareTo = constraints[condition];
  152. if (compareTo.__type) {
  153. compareTo = decode(compareTo);
  154. } // Compare Date Object or Date String
  155. if (toString.call(compareTo) === '[object Date]' || typeof compareTo === 'string' && new Date(compareTo) !== 'Invalid Date' && !isNaN(new Date(compareTo))) {
  156. object[key] = new Date(object[key].iso ? object[key].iso : object[key]);
  157. }
  158. switch (condition) {
  159. case '$lt':
  160. if (object[key] >= compareTo) {
  161. return false;
  162. }
  163. break;
  164. case '$lte':
  165. if (object[key] > compareTo) {
  166. return false;
  167. }
  168. break;
  169. case '$gt':
  170. if (object[key] <= compareTo) {
  171. return false;
  172. }
  173. break;
  174. case '$gte':
  175. if (object[key] < compareTo) {
  176. return false;
  177. }
  178. break;
  179. case '$ne':
  180. if (equalObjects(object[key], compareTo)) {
  181. return false;
  182. }
  183. break;
  184. case '$in':
  185. if (!contains(compareTo, object[key])) {
  186. return false;
  187. }
  188. break;
  189. case '$nin':
  190. if (contains(compareTo, object[key])) {
  191. return false;
  192. }
  193. break;
  194. case '$all':
  195. for (i = 0; i < compareTo.length; i++) {
  196. if (object[key].indexOf(compareTo[i]) < 0) {
  197. return false;
  198. }
  199. }
  200. break;
  201. case '$exists':
  202. {
  203. const propertyExists = typeof object[key] !== 'undefined';
  204. const existenceIsRequired = constraints.$exists;
  205. if (typeof constraints.$exists !== 'boolean') {
  206. // The SDK will never submit a non-boolean for $exists, but if someone
  207. // tries to submit a non-boolean for $exits outside the SDKs, just ignore it.
  208. break;
  209. }
  210. if (!propertyExists && existenceIsRequired || propertyExists && !existenceIsRequired) {
  211. return false;
  212. }
  213. break;
  214. }
  215. case '$regex':
  216. {
  217. if (typeof compareTo === 'object') {
  218. return compareTo.test(object[key]);
  219. } // JS doesn't support perl-style escaping
  220. let expString = '';
  221. let escapeEnd = -2;
  222. let escapeStart = compareTo.indexOf('\\Q');
  223. while (escapeStart > -1) {
  224. // Add the unescaped portion
  225. expString += compareTo.substring(escapeEnd + 2, escapeStart);
  226. escapeEnd = compareTo.indexOf('\\E', escapeStart);
  227. if (escapeEnd > -1) {
  228. expString += compareTo.substring(escapeStart + 2, escapeEnd).replace(/\\\\\\\\E/g, '\\E').replace(/\W/g, '\\$&');
  229. }
  230. escapeStart = compareTo.indexOf('\\Q', escapeEnd);
  231. }
  232. expString += compareTo.substring(Math.max(escapeStart, escapeEnd + 2));
  233. let modifiers = constraints.$options || '';
  234. modifiers = modifiers.replace('x', '').replace('s', ''); // Parse Server / Mongo support x and s modifiers but JS RegExp doesn't
  235. const exp = new RegExp(expString, modifiers);
  236. if (!exp.test(object[key])) {
  237. return false;
  238. }
  239. break;
  240. }
  241. case '$nearSphere':
  242. {
  243. if (!compareTo || !object[key]) {
  244. return false;
  245. }
  246. const distance = compareTo.radiansTo(object[key]);
  247. const max = constraints.$maxDistance || Infinity;
  248. return distance <= max;
  249. }
  250. case '$within':
  251. {
  252. if (!compareTo || !object[key]) {
  253. return false;
  254. }
  255. const southWest = compareTo.$box[0];
  256. const northEast = compareTo.$box[1];
  257. if (southWest.latitude > northEast.latitude || southWest.longitude > northEast.longitude) {
  258. // Invalid box, crosses the date line
  259. return false;
  260. }
  261. return object[key].latitude > southWest.latitude && object[key].latitude < northEast.latitude && object[key].longitude > southWest.longitude && object[key].longitude < northEast.longitude;
  262. }
  263. case '$options':
  264. // Not a query type, but a way to add options to $regex. Ignore and
  265. // avoid the default
  266. break;
  267. case '$maxDistance':
  268. // Not a query type, but a way to add a cap to $nearSphere. Ignore and
  269. // avoid the default
  270. break;
  271. case '$select':
  272. {
  273. const subQueryObjects = objects.filter((obj, index, arr) => {
  274. return matchesQuery(compareTo.query.className, obj, arr, compareTo.query.where);
  275. });
  276. for (let i = 0; i < subQueryObjects.length; i += 1) {
  277. const subObject = transformObject(subQueryObjects[i]);
  278. return equalObjects(object[key], subObject[compareTo.key]);
  279. }
  280. return false;
  281. }
  282. case '$dontSelect':
  283. {
  284. const subQueryObjects = objects.filter((obj, index, arr) => {
  285. return matchesQuery(compareTo.query.className, obj, arr, compareTo.query.where);
  286. });
  287. for (let i = 0; i < subQueryObjects.length; i += 1) {
  288. const subObject = transformObject(subQueryObjects[i]);
  289. return !equalObjects(object[key], subObject[compareTo.key]);
  290. }
  291. return false;
  292. }
  293. case '$inQuery':
  294. {
  295. const subQueryObjects = objects.filter((obj, index, arr) => {
  296. return matchesQuery(compareTo.className, obj, arr, compareTo.where);
  297. });
  298. for (let i = 0; i < subQueryObjects.length; i += 1) {
  299. const subObject = transformObject(subQueryObjects[i]);
  300. if (object[key].className === subObject.className && object[key].objectId === subObject.objectId) {
  301. return true;
  302. }
  303. }
  304. return false;
  305. }
  306. case '$notInQuery':
  307. {
  308. const subQueryObjects = objects.filter((obj, index, arr) => {
  309. return matchesQuery(compareTo.className, obj, arr, compareTo.where);
  310. });
  311. for (let i = 0; i < subQueryObjects.length; i += 1) {
  312. const subObject = transformObject(subQueryObjects[i]);
  313. if (object[key].className === subObject.className && object[key].objectId === subObject.objectId) {
  314. return false;
  315. }
  316. }
  317. return true;
  318. }
  319. case '$containedBy':
  320. {
  321. for (const value of object[key]) {
  322. if (!contains(compareTo, value)) {
  323. return false;
  324. }
  325. }
  326. return true;
  327. }
  328. case '$geoWithin':
  329. {
  330. const points = compareTo.$polygon.map(geoPoint => [geoPoint.latitude, geoPoint.longitude]);
  331. const polygon = new ParsePolygon(points);
  332. return polygon.containsPoint(object[key]);
  333. }
  334. case '$geoIntersects':
  335. {
  336. const polygon = new ParsePolygon(object[key].coordinates);
  337. const point = new ParseGeoPoint(compareTo.$point);
  338. return polygon.containsPoint(point);
  339. }
  340. default:
  341. return false;
  342. }
  343. }
  344. return true;
  345. }
  346. function validateQuery(query
  347. /*: any*/
  348. ) {
  349. let q = query;
  350. if (query.toJSON) {
  351. q = query.toJSON().where;
  352. }
  353. const specialQuerykeys = ['$and', '$or', '$nor', '_rperm', '_wperm', '_perishable_token', '_email_verify_token', '_email_verify_token_expires_at', '_account_lockout_expires_at', '_failed_login_count'];
  354. Object.keys(q).forEach(key => {
  355. if (q && q[key] && q[key].$regex) {
  356. if (typeof q[key].$options === 'string') {
  357. if (!q[key].$options.match(/^[imxs]+$/)) {
  358. throw new ParseError(ParseError.INVALID_QUERY, `Bad $options value for query: ${q[key].$options}`);
  359. }
  360. }
  361. }
  362. if (specialQuerykeys.indexOf(key) < 0 && !key.match(/^[a-zA-Z][a-zA-Z0-9_.]*$/)) {
  363. throw new ParseError(ParseError.INVALID_KEY_NAME, `Invalid key name: ${key}`);
  364. }
  365. });
  366. }
  367. const OfflineQuery = {
  368. matchesQuery: matchesQuery,
  369. validateQuery: validateQuery
  370. };
  371. module.exports = OfflineQuery;