OfflineQuery.js 12 KB

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