OfflineQuery.js 12 KB

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