ParseQuery.js 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  7. var _encode = _interopRequireDefault(require("./encode"));
  8. var _promiseUtils = require("./promiseUtils");
  9. var _ParseError = _interopRequireDefault(require("./ParseError"));
  10. var _ParseGeoPoint = _interopRequireDefault(require("./ParseGeoPoint"));
  11. var _ParseObject = _interopRequireDefault(require("./ParseObject"));
  12. var _OfflineQuery = _interopRequireDefault(require("./OfflineQuery"));
  13. var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
  14. function _interopRequireDefault(e) {
  15. return e && e.__esModule ? e : {
  16. default: e
  17. };
  18. }
  19. /**
  20. * Converts a string into a regex that matches it.
  21. * Surrounding with \Q .. \E does this, we just need to escape any \E's in
  22. * the text separately.
  23. *
  24. * @param s
  25. * @private
  26. * @returns {string}
  27. */
  28. function quote(s) {
  29. return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E';
  30. }
  31. /**
  32. * Extracts the class name from queries. If not all queries have the same
  33. * class name an error will be thrown.
  34. *
  35. * @param queries
  36. * @private
  37. * @returns {string}
  38. */
  39. function _getClassNameFromQueries(queries) {
  40. let className = null;
  41. queries.forEach(q => {
  42. if (!className) {
  43. className = q.className;
  44. }
  45. if (className !== q.className) {
  46. throw new Error('All queries must be for the same class.');
  47. }
  48. });
  49. return className;
  50. }
  51. /*
  52. * Handles pre-populating the result data of a query with select fields,
  53. * making sure that the data object contains keys for all objects that have
  54. * been requested with a select, so that our cached state updates correctly.
  55. */
  56. function handleSelectResult(data, select) {
  57. const serverDataMask = {};
  58. select.forEach(field => {
  59. const hasSubObjectSelect = field.indexOf('.') !== -1;
  60. if (!hasSubObjectSelect && !data.hasOwnProperty(field)) {
  61. // this field was selected, but is missing from the retrieved data
  62. data[field] = undefined;
  63. } else if (hasSubObjectSelect) {
  64. // this field references a sub-object,
  65. // so we need to walk down the path components
  66. const pathComponents = field.split('.');
  67. let obj = data;
  68. let serverMask = serverDataMask;
  69. pathComponents.forEach((component, index, arr) => {
  70. // add keys if the expected data is missing
  71. if (obj && !obj.hasOwnProperty(component)) {
  72. obj[component] = undefined;
  73. }
  74. if (obj && typeof obj === 'object') {
  75. obj = obj[component];
  76. }
  77. //add this path component to the server mask so we can fill it in later if needed
  78. if (index < arr.length - 1) {
  79. if (!serverMask[component]) {
  80. serverMask[component] = {};
  81. }
  82. serverMask = serverMask[component];
  83. }
  84. });
  85. }
  86. });
  87. if (Object.keys(serverDataMask).length > 0) {
  88. // When selecting from sub-objects, we don't want to blow away the missing
  89. // information that we may have retrieved before. We've already added any
  90. // missing selected keys to sub-objects, but we still need to add in the
  91. // data for any previously retrieved sub-objects that were not selected.
  92. const serverData = _CoreManager.default.getObjectStateController().getServerData({
  93. id: data.objectId,
  94. className: data.className
  95. });
  96. copyMissingDataWithMask(serverData, data, serverDataMask, false);
  97. }
  98. }
  99. function copyMissingDataWithMask(src, dest, mask, copyThisLevel) {
  100. //copy missing elements at this level
  101. if (copyThisLevel) {
  102. for (const key in src) {
  103. if (src.hasOwnProperty(key) && !dest.hasOwnProperty(key)) {
  104. dest[key] = src[key];
  105. }
  106. }
  107. }
  108. for (const key in mask) {
  109. if (dest[key] !== undefined && dest[key] !== null && src !== undefined && src !== null) {
  110. //traverse into objects as needed
  111. copyMissingDataWithMask(src[key], dest[key], mask[key], true);
  112. }
  113. }
  114. }
  115. function handleOfflineSort(a, b, sorts) {
  116. let order = sorts[0];
  117. const operator = order.slice(0, 1);
  118. const isDescending = operator === '-';
  119. if (isDescending) {
  120. order = order.substring(1);
  121. }
  122. if (order === '_created_at') {
  123. order = 'createdAt';
  124. }
  125. if (order === '_updated_at') {
  126. order = 'updatedAt';
  127. }
  128. if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(order) || order === 'password') {
  129. throw new _ParseError.default(_ParseError.default.INVALID_KEY_NAME, `Invalid Key: ${order}`);
  130. }
  131. const field1 = a.get(order);
  132. const field2 = b.get(order);
  133. if (field1 < field2) {
  134. return isDescending ? 1 : -1;
  135. }
  136. if (field1 > field2) {
  137. return isDescending ? -1 : 1;
  138. }
  139. if (sorts.length > 1) {
  140. const remainingSorts = sorts.slice(1);
  141. return handleOfflineSort(a, b, remainingSorts);
  142. }
  143. return 0;
  144. }
  145. /**
  146. * Creates a new parse Parse.Query for the given Parse.Object subclass.
  147. *
  148. * <p>Parse.Query defines a query that is used to fetch Parse.Objects. The
  149. * most common use case is finding all objects that match a query through the
  150. * <code>find</code> method. for example, this sample code fetches all objects
  151. * of class <code>myclass</code>. it calls a different function depending on
  152. * whether the fetch succeeded or not.
  153. *
  154. * <pre>
  155. * var query = new Parse.Query(myclass);
  156. * query.find().then((results) => {
  157. * // results is an array of parse.object.
  158. * }).catch((error) => {
  159. * // error is an instance of parse.error.
  160. * });</pre></p>
  161. *
  162. * <p>a Parse.Query can also be used to retrieve a single object whose id is
  163. * known, through the get method. for example, this sample code fetches an
  164. * object of class <code>myclass</code> and id <code>myid</code>. it calls a
  165. * different function depending on whether the fetch succeeded or not.
  166. *
  167. * <pre>
  168. * var query = new Parse.Query(myclass);
  169. * query.get(myid).then((object) => {
  170. * // object is an instance of parse.object.
  171. * }).catch((error) => {
  172. * // error is an instance of parse.error.
  173. * });</pre></p>
  174. *
  175. * <p>a Parse.Query can also be used to count the number of objects that match
  176. * the query without retrieving all of those objects. for example, this
  177. * sample code counts the number of objects of the class <code>myclass</code>
  178. * <pre>
  179. * var query = new Parse.Query(myclass);
  180. * query.count().then((number) => {
  181. * // there are number instances of myclass.
  182. * }).catch((error) => {
  183. * // error is an instance of Parse.Error.
  184. * });</pre></p>
  185. *
  186. * @alias Parse.Query
  187. */
  188. class ParseQuery {
  189. /**
  190. * @property {string} className
  191. */
  192. /**
  193. * @param {(string | Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string.
  194. */
  195. constructor(objectClass) {
  196. if (typeof objectClass === 'string') {
  197. if (objectClass === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  198. this.className = '_User';
  199. } else {
  200. this.className = objectClass;
  201. }
  202. } else if (objectClass instanceof _ParseObject.default) {
  203. this.className = objectClass.className;
  204. } else if (typeof objectClass === 'function') {
  205. const objClass = objectClass;
  206. if (typeof objClass.className === 'string') {
  207. this.className = objClass.className;
  208. } else {
  209. const obj = new objClass();
  210. this.className = obj.className;
  211. }
  212. } else {
  213. throw new TypeError('A ParseQuery must be constructed with a ParseObject or class name.');
  214. }
  215. this._where = {};
  216. this._watch = [];
  217. this._include = [];
  218. this._exclude = [];
  219. this._count = false;
  220. this._limit = -1; // negative limit is not sent in the server request
  221. this._skip = 0;
  222. this._readPreference = null;
  223. this._includeReadPreference = null;
  224. this._subqueryReadPreference = null;
  225. this._queriesLocalDatastore = false;
  226. this._localDatastorePinName = null;
  227. this._extraOptions = {};
  228. this._xhrRequest = {
  229. task: null,
  230. onchange: () => {}
  231. };
  232. this._comment = null;
  233. }
  234. /**
  235. * Adds constraint that at least one of the passed in queries matches.
  236. *
  237. * @param {Array} queries
  238. * @returns {Parse.Query} Returns the query, so you can chain this call.
  239. */
  240. _orQuery(queries) {
  241. const queryJSON = queries.map(q => {
  242. return q.toJSON().where;
  243. });
  244. this._where.$or = queryJSON;
  245. return this;
  246. }
  247. /**
  248. * Adds constraint that all of the passed in queries match.
  249. *
  250. * @param {Array} queries
  251. * @returns {Parse.Query} Returns the query, so you can chain this call.
  252. */
  253. _andQuery(queries) {
  254. const queryJSON = queries.map(q => {
  255. return q.toJSON().where;
  256. });
  257. this._where.$and = queryJSON;
  258. return this;
  259. }
  260. /**
  261. * Adds constraint that none of the passed in queries match.
  262. *
  263. * @param {Array} queries
  264. * @returns {Parse.Query} Returns the query, so you can chain this call.
  265. */
  266. _norQuery(queries) {
  267. const queryJSON = queries.map(q => {
  268. return q.toJSON().where;
  269. });
  270. this._where.$nor = queryJSON;
  271. return this;
  272. }
  273. /**
  274. * Helper for condition queries
  275. *
  276. * @param key
  277. * @param condition
  278. * @param value
  279. * @returns {Parse.Query}
  280. */
  281. _addCondition(key, condition, value) {
  282. if (!this._where[key] || typeof this._where[key] === 'string') {
  283. this._where[key] = {};
  284. }
  285. this._where[key][condition] = (0, _encode.default)(value, false, true);
  286. return this;
  287. }
  288. /**
  289. * Converts string for regular expression at the beginning
  290. *
  291. * @param string
  292. * @returns {string}
  293. */
  294. _regexStartWith(string) {
  295. return '^' + quote(string);
  296. }
  297. async _handleOfflineQuery(params) {
  298. _OfflineQuery.default.validateQuery(this);
  299. const localDatastore = _CoreManager.default.getLocalDatastore();
  300. const objects = await localDatastore._serializeObjectsFromPinName(this._localDatastorePinName);
  301. let results = objects.map((json, index, arr) => {
  302. const object = _ParseObject.default.fromJSON(json, false);
  303. if (json._localId && !json.objectId) {
  304. object._localId = json._localId;
  305. }
  306. if (!_OfflineQuery.default.matchesQuery(this.className, object, arr, this)) {
  307. return null;
  308. }
  309. return object;
  310. }).filter(object => object !== null);
  311. if (params.keys) {
  312. let keys = params.keys.split(',');
  313. keys = keys.concat(['className', 'objectId', 'createdAt', 'updatedAt', 'ACL']);
  314. results = results.map(object => {
  315. const json = object._toFullJSON();
  316. Object.keys(json).forEach(key => {
  317. if (!keys.includes(key)) {
  318. delete json[key];
  319. }
  320. });
  321. return _ParseObject.default.fromJSON(json, false);
  322. });
  323. }
  324. if (params.order) {
  325. const sorts = params.order.split(',');
  326. results.sort((a, b) => {
  327. return handleOfflineSort(a, b, sorts);
  328. });
  329. }
  330. let count; // count total before applying limit/skip
  331. if (params.count) {
  332. count = results.length; // total count from response
  333. }
  334. if (params.skip) {
  335. if (params.skip >= results.length) {
  336. results = [];
  337. } else {
  338. results = results.splice(params.skip, results.length);
  339. }
  340. }
  341. let limit = results.length;
  342. if (params.limit !== 0 && params.limit < results.length) {
  343. limit = params.limit;
  344. }
  345. results = results.splice(0, limit);
  346. if (typeof count === 'number') {
  347. return {
  348. results,
  349. count
  350. };
  351. }
  352. return results;
  353. }
  354. /**
  355. * Returns a JSON representation of this query.
  356. *
  357. * @returns {object} The JSON representation of the query.
  358. */
  359. toJSON() {
  360. const params = {
  361. where: this._where
  362. };
  363. if (this._watch.length) {
  364. params.watch = this._watch.join(',');
  365. }
  366. if (this._include.length) {
  367. params.include = this._include.join(',');
  368. }
  369. if (this._exclude.length) {
  370. params.excludeKeys = this._exclude.join(',');
  371. }
  372. if (this._select) {
  373. params.keys = this._select.join(',');
  374. }
  375. if (this._count) {
  376. params.count = 1;
  377. }
  378. if (this._limit >= 0) {
  379. params.limit = this._limit;
  380. }
  381. if (this._skip > 0) {
  382. params.skip = this._skip;
  383. }
  384. if (this._order) {
  385. params.order = this._order.join(',');
  386. }
  387. if (this._readPreference) {
  388. params.readPreference = this._readPreference;
  389. }
  390. if (this._includeReadPreference) {
  391. params.includeReadPreference = this._includeReadPreference;
  392. }
  393. if (this._subqueryReadPreference) {
  394. params.subqueryReadPreference = this._subqueryReadPreference;
  395. }
  396. if (this._hint) {
  397. params.hint = this._hint;
  398. }
  399. if (this._explain) {
  400. params.explain = true;
  401. }
  402. if (this._comment) {
  403. params.comment = this._comment;
  404. }
  405. for (const key in this._extraOptions) {
  406. params[key] = this._extraOptions[key];
  407. }
  408. return params;
  409. }
  410. /**
  411. * Return a query with conditions from json, can be useful to send query from server side to client
  412. * Not static, all query conditions was set before calling this method will be deleted.
  413. * For example on the server side we have
  414. * var query = new Parse.Query("className");
  415. * query.equalTo(key: value);
  416. * query.limit(100);
  417. * ... (others queries)
  418. * Create JSON representation of Query Object
  419. * var jsonFromServer = query.fromJSON();
  420. *
  421. * On client side getting query:
  422. * var query = new Parse.Query("className");
  423. * query.fromJSON(jsonFromServer);
  424. *
  425. * and continue to query...
  426. * query.skip(100).find().then(...);
  427. *
  428. * @param {QueryJSON} json from Parse.Query.toJSON() method
  429. * @returns {Parse.Query} Returns the query, so you can chain this call.
  430. */
  431. withJSON(json) {
  432. if (json.where) {
  433. this._where = json.where;
  434. }
  435. if (json.watch) {
  436. this._watch = json.watch.split(',');
  437. }
  438. if (json.include) {
  439. this._include = json.include.split(',');
  440. }
  441. if (json.keys) {
  442. this._select = json.keys.split(',');
  443. }
  444. if (json.excludeKeys) {
  445. this._exclude = json.excludeKeys.split(',');
  446. }
  447. if (json.count) {
  448. this._count = json.count === 1;
  449. }
  450. if (json.limit) {
  451. this._limit = json.limit;
  452. }
  453. if (json.skip) {
  454. this._skip = json.skip;
  455. }
  456. if (json.order) {
  457. this._order = json.order.split(',');
  458. }
  459. if (json.readPreference) {
  460. this._readPreference = json.readPreference;
  461. }
  462. if (json.includeReadPreference) {
  463. this._includeReadPreference = json.includeReadPreference;
  464. }
  465. if (json.subqueryReadPreference) {
  466. this._subqueryReadPreference = json.subqueryReadPreference;
  467. }
  468. if (json.hint) {
  469. this._hint = json.hint;
  470. }
  471. if (json.explain) {
  472. this._explain = !!json.explain;
  473. }
  474. if (json.comment) {
  475. this._comment = json.comment;
  476. }
  477. for (const key in json) {
  478. if (json.hasOwnProperty(key)) {
  479. if (['where', 'include', 'keys', 'count', 'limit', 'skip', 'order', 'readPreference', 'includeReadPreference', 'subqueryReadPreference', 'hint', 'explain', 'comment'].indexOf(key) === -1) {
  480. this._extraOptions[key] = json[key];
  481. }
  482. }
  483. }
  484. return this;
  485. }
  486. /**
  487. * Static method to restore Parse.Query by json representation
  488. * Internally calling Parse.Query.withJSON
  489. *
  490. * @param {string} className
  491. * @param {QueryJSON} json from Parse.Query.toJSON() method
  492. * @returns {Parse.Query} new created query
  493. */
  494. static fromJSON(className, json) {
  495. const query = new ParseQuery(className);
  496. return query.withJSON(json);
  497. }
  498. /**
  499. * Constructs a Parse.Object whose id is already known by fetching data from
  500. * the server. Unlike the <code>first</code> method, it never returns undefined.
  501. *
  502. * @param {string} objectId The id of the object to be fetched.
  503. * @param {object} options
  504. * Valid options are:<ul>
  505. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  506. * be used for this request.
  507. * <li>sessionToken: A valid session token, used for making a request on
  508. * behalf of a specific user.
  509. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  510. * <li>json: Return raw json without converting to Parse.Object
  511. * </ul>
  512. * @returns {Promise} A promise that is resolved with the result when
  513. * the query completes.
  514. */
  515. get(objectId, options) {
  516. this.equalTo('objectId', objectId);
  517. const firstOptions = {};
  518. if (options && options.hasOwnProperty('useMasterKey')) {
  519. firstOptions.useMasterKey = options.useMasterKey;
  520. }
  521. if (options && options.hasOwnProperty('sessionToken')) {
  522. firstOptions.sessionToken = options.sessionToken;
  523. }
  524. if (options && options.hasOwnProperty('context') && typeof options.context === 'object') {
  525. firstOptions.context = options.context;
  526. }
  527. if (options && options.hasOwnProperty('json')) {
  528. firstOptions.json = options.json;
  529. }
  530. return this.first(firstOptions).then(response => {
  531. if (response) {
  532. return response;
  533. }
  534. const errorObject = new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'Object not found.');
  535. return Promise.reject(errorObject);
  536. });
  537. }
  538. /**
  539. * Retrieves a list of ParseObjects that satisfy this query.
  540. *
  541. * @param {object} options Valid options
  542. * are:<ul>
  543. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  544. * be used for this request.
  545. * <li>sessionToken: A valid session token, used for making a request on
  546. * behalf of a specific user.
  547. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  548. * <li>json: Return raw json without converting to Parse.Object
  549. * </ul>
  550. * @returns {Promise} A promise that is resolved with the results when
  551. * the query completes.
  552. */
  553. find(options) {
  554. options = options || {};
  555. const findOptions = {};
  556. if (options.hasOwnProperty('useMasterKey')) {
  557. findOptions.useMasterKey = options.useMasterKey;
  558. }
  559. if (options.hasOwnProperty('sessionToken')) {
  560. findOptions.sessionToken = options.sessionToken;
  561. }
  562. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  563. findOptions.context = options.context;
  564. }
  565. this._setRequestTask(findOptions);
  566. const controller = _CoreManager.default.getQueryController();
  567. const select = this._select;
  568. if (this._queriesLocalDatastore) {
  569. return this._handleOfflineQuery(this.toJSON());
  570. }
  571. return controller.find(this.className, this.toJSON(), findOptions).then(response => {
  572. var _response$results;
  573. // Return generic object when explain is used
  574. if (this._explain) {
  575. return response.results;
  576. }
  577. const results = (_response$results = response.results) === null || _response$results === void 0 ? void 0 : _response$results.map(data => {
  578. // In cases of relations, the server may send back a className
  579. // on the top level of the payload
  580. const override = response.className || this.className;
  581. if (!data.className) {
  582. data.className = override;
  583. }
  584. // Make sure the data object contains keys for all objects that
  585. // have been requested with a select, so that our cached state
  586. // updates correctly.
  587. if (select) {
  588. handleSelectResult(data, select);
  589. }
  590. if (options.json) {
  591. return data;
  592. } else {
  593. return _ParseObject.default.fromJSON(data, !select);
  594. }
  595. });
  596. const count = response.count;
  597. if (typeof count === 'number') {
  598. return {
  599. results,
  600. count
  601. };
  602. } else {
  603. return results;
  604. }
  605. });
  606. }
  607. /**
  608. * Retrieves a complete list of ParseObjects that satisfy this query.
  609. * Using `eachBatch` under the hood to fetch all the valid objects.
  610. *
  611. * @param {object} options Valid options are:<ul>
  612. * <li>batchSize: How many objects to yield in each batch (default: 100)
  613. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  614. * be used for this request.
  615. * <li>sessionToken: A valid session token, used for making a request on
  616. * behalf of a specific user.
  617. * </ul>
  618. * @returns {Promise} A promise that is resolved with the results when
  619. * the query completes.
  620. */
  621. async findAll(options) {
  622. let result = [];
  623. await this.eachBatch(objects => {
  624. result = [...result, ...objects];
  625. }, options);
  626. return result;
  627. }
  628. /**
  629. * Counts the number of objects that match this query.
  630. *
  631. * @param {object} options
  632. * @param {boolean} [options.useMasterKey]
  633. * @param {string} [options.sessionToken]
  634. * Valid options are:<ul>
  635. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  636. * be used for this request.
  637. * <li>sessionToken: A valid session token, used for making a request on
  638. * behalf of a specific user.
  639. * </ul>
  640. * @returns {Promise} A promise that is resolved with the count when
  641. * the query completes.
  642. */
  643. count(options) {
  644. options = options || {};
  645. const findOptions = {};
  646. if (options.hasOwnProperty('useMasterKey')) {
  647. findOptions.useMasterKey = options.useMasterKey;
  648. }
  649. if (options.hasOwnProperty('sessionToken')) {
  650. findOptions.sessionToken = options.sessionToken;
  651. }
  652. this._setRequestTask(findOptions);
  653. const controller = _CoreManager.default.getQueryController();
  654. const params = this.toJSON();
  655. params.limit = 0;
  656. params.count = 1;
  657. return controller.find(this.className, params, findOptions).then(result => {
  658. return result.count;
  659. });
  660. }
  661. /**
  662. * Executes a distinct query and returns unique values
  663. *
  664. * @param {string} key A field to find distinct values
  665. * @param {object} options
  666. * @param {string} [options.sessionToken] A valid session token, used for making a request on behalf of a specific user.
  667. * @returns {Promise} A promise that is resolved with the query completes.
  668. */
  669. distinct(key, options) {
  670. options = options || {};
  671. const distinctOptions = {
  672. useMasterKey: true
  673. };
  674. if (options.hasOwnProperty('sessionToken')) {
  675. distinctOptions.sessionToken = options.sessionToken;
  676. }
  677. this._setRequestTask(distinctOptions);
  678. const controller = _CoreManager.default.getQueryController();
  679. const params = {
  680. distinct: key,
  681. where: this._where,
  682. hint: this._hint
  683. };
  684. return controller.aggregate(this.className, params, distinctOptions).then(results => {
  685. return results.results;
  686. });
  687. }
  688. /**
  689. * Executes an aggregate query and returns aggregate results
  690. *
  691. * @param {(Array|object)} pipeline Array or Object of stages to process query
  692. * @param {object} options
  693. * @param {string} [options.sessionToken] A valid session token, used for making a request on behalf of a specific user.
  694. * @returns {Promise} A promise that is resolved with the query completes.
  695. */
  696. aggregate(pipeline, options) {
  697. options = options || {};
  698. const aggregateOptions = {
  699. useMasterKey: true
  700. };
  701. if (options.hasOwnProperty('sessionToken')) {
  702. aggregateOptions.sessionToken = options.sessionToken;
  703. }
  704. this._setRequestTask(aggregateOptions);
  705. const controller = _CoreManager.default.getQueryController();
  706. if (!Array.isArray(pipeline) && typeof pipeline !== 'object') {
  707. throw new Error('Invalid pipeline must be Array or Object');
  708. }
  709. if (Object.keys(this._where || {}).length) {
  710. if (!Array.isArray(pipeline)) {
  711. pipeline = [pipeline];
  712. }
  713. pipeline.unshift({
  714. $match: this._where
  715. });
  716. }
  717. const params = {
  718. pipeline,
  719. hint: this._hint,
  720. explain: this._explain,
  721. readPreference: this._readPreference
  722. };
  723. return controller.aggregate(this.className, params, aggregateOptions).then(results => {
  724. return results.results;
  725. });
  726. }
  727. /**
  728. * Retrieves at most one Parse.Object that satisfies this query.
  729. *
  730. * Returns the object if there is one, otherwise undefined.
  731. *
  732. * @param {object} options Valid options are:<ul>
  733. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  734. * be used for this request.
  735. * <li>sessionToken: A valid session token, used for making a request on
  736. * behalf of a specific user.
  737. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  738. * <li>json: Return raw json without converting to Parse.Object
  739. * </ul>
  740. * @returns {Promise} A promise that is resolved with the object when
  741. * the query completes.
  742. */
  743. first(options = {}) {
  744. const findOptions = {};
  745. if (options.hasOwnProperty('useMasterKey')) {
  746. findOptions.useMasterKey = options.useMasterKey;
  747. }
  748. if (options.hasOwnProperty('sessionToken')) {
  749. findOptions.sessionToken = options.sessionToken;
  750. }
  751. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  752. findOptions.context = options.context;
  753. }
  754. this._setRequestTask(findOptions);
  755. const controller = _CoreManager.default.getQueryController();
  756. const params = this.toJSON();
  757. params.limit = 1;
  758. const select = this._select;
  759. if (this._queriesLocalDatastore) {
  760. return this._handleOfflineQuery(params).then(objects => {
  761. if (!objects[0]) {
  762. return undefined;
  763. }
  764. return objects[0];
  765. });
  766. }
  767. return controller.find(this.className, params, findOptions).then(response => {
  768. const objects = response.results;
  769. if (!objects[0]) {
  770. return undefined;
  771. }
  772. if (!objects[0].className) {
  773. objects[0].className = this.className;
  774. }
  775. // Make sure the data object contains keys for all objects that
  776. // have been requested with a select, so that our cached state
  777. // updates correctly.
  778. if (select) {
  779. handleSelectResult(objects[0], select);
  780. }
  781. if (options.json) {
  782. return objects[0];
  783. } else {
  784. return _ParseObject.default.fromJSON(objects[0], !select);
  785. }
  786. });
  787. }
  788. /**
  789. * Iterates over objects matching a query, calling a callback for each batch.
  790. * If the callback returns a promise, the iteration will not continue until
  791. * that promise has been fulfilled. If the callback returns a rejected
  792. * promise, then iteration will stop with that error. The items are processed
  793. * in an unspecified order. The query may not have any sort order, and may
  794. * not use limit or skip.
  795. *
  796. * @param {Function} callback Callback that will be called with each result
  797. * of the query.
  798. * @param {object} options Valid options are:<ul>
  799. * <li>batchSize: How many objects to yield in each batch (default: 100)
  800. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  801. * be used for this request.
  802. * <li>sessionToken: A valid session token, used for making a request on
  803. * behalf of a specific user.
  804. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  805. * </ul>
  806. * @returns {Promise} A promise that will be fulfilled once the
  807. * iteration has completed.
  808. */
  809. eachBatch(callback, options) {
  810. options = options || {};
  811. if (this._order || this._skip || this._limit >= 0) {
  812. return Promise.reject('Cannot iterate on a query with sort, skip, or limit.');
  813. }
  814. const query = new ParseQuery(this.className);
  815. query._limit = options.batchSize || 100;
  816. query._include = [...this._include];
  817. query._exclude = [...this._exclude];
  818. if (this._select) {
  819. query._select = [...this._select];
  820. }
  821. query._hint = this._hint;
  822. query._where = {};
  823. for (const attr in this._where) {
  824. const val = this._where[attr];
  825. if (Array.isArray(val)) {
  826. query._where[attr] = val.map(v => {
  827. return v;
  828. });
  829. } else if (val && typeof val === 'object') {
  830. const conditionMap = {};
  831. query._where[attr] = conditionMap;
  832. for (const cond in val) {
  833. conditionMap[cond] = val[cond];
  834. }
  835. } else {
  836. query._where[attr] = val;
  837. }
  838. }
  839. query.ascending('objectId');
  840. const findOptions = {};
  841. if (options.hasOwnProperty('useMasterKey')) {
  842. findOptions.useMasterKey = options.useMasterKey;
  843. }
  844. if (options.hasOwnProperty('sessionToken')) {
  845. findOptions.sessionToken = options.sessionToken;
  846. }
  847. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  848. findOptions.context = options.context;
  849. }
  850. if (options.hasOwnProperty('json')) {
  851. findOptions.json = options.json;
  852. }
  853. let finished = false;
  854. let previousResults = [];
  855. return (0, _promiseUtils.continueWhile)(() => {
  856. return !finished;
  857. }, async () => {
  858. const [results] = await Promise.all([query.find(findOptions), Promise.resolve(previousResults.length > 0 && callback(previousResults))]);
  859. if (results.length >= query._limit) {
  860. query.greaterThan('objectId', results[results.length - 1].id);
  861. previousResults = results;
  862. } else if (results.length > 0) {
  863. await Promise.resolve(callback(results));
  864. finished = true;
  865. } else {
  866. finished = true;
  867. }
  868. });
  869. }
  870. /**
  871. * Iterates over each result of a query, calling a callback for each one. If
  872. * the callback returns a promise, the iteration will not continue until
  873. * that promise has been fulfilled. If the callback returns a rejected
  874. * promise, then iteration will stop with that error. The items are
  875. * processed in an unspecified order. The query may not have any sort order,
  876. * and may not use limit or skip.
  877. *
  878. * @param {Function} callback Callback that will be called with each result
  879. * of the query.
  880. * @param {object} options Valid options are:<ul>
  881. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  882. * be used for this request.
  883. * <li>sessionToken: A valid session token, used for making a request on
  884. * behalf of a specific user.
  885. * <li>json: Return raw json without converting to Parse.Object
  886. * </ul>
  887. * @returns {Promise} A promise that will be fulfilled once the
  888. * iteration has completed.
  889. */
  890. each(callback, options) {
  891. return this.eachBatch(results => {
  892. let callbacksDone = Promise.resolve();
  893. results.forEach(result => {
  894. callbacksDone = callbacksDone.then(() => {
  895. return callback(result);
  896. });
  897. });
  898. return callbacksDone;
  899. }, options);
  900. }
  901. /**
  902. * Adds a hint to force index selection. (https://docs.mongodb.com/manual/reference/operator/meta/hint/)
  903. *
  904. * @param {(string|object)} value String or Object of index that should be used when executing query
  905. * @returns {Parse.Query} Returns the query, so you can chain this call.
  906. */
  907. hint(value) {
  908. if (typeof value === 'undefined') {
  909. delete this._hint;
  910. }
  911. this._hint = value;
  912. return this;
  913. }
  914. /**
  915. * Investigates the query execution plan. Useful for optimizing queries. (https://docs.mongodb.com/manual/reference/operator/meta/explain/)
  916. *
  917. * @param {boolean} explain Used to toggle the information on the query plan.
  918. * @returns {Parse.Query} Returns the query, so you can chain this call.
  919. */
  920. explain(explain = true) {
  921. if (typeof explain !== 'boolean') {
  922. throw new Error('You can only set explain to a boolean value');
  923. }
  924. this._explain = explain;
  925. return this;
  926. }
  927. /**
  928. * Iterates over each result of a query, calling a callback for each one. If
  929. * the callback returns a promise, the iteration will not continue until
  930. * that promise has been fulfilled. If the callback returns a rejected
  931. * promise, then iteration will stop with that error. The items are
  932. * processed in an unspecified order. The query may not have any sort order,
  933. * and may not use limit or skip.
  934. *
  935. * @param {Function} callback Callback <ul>
  936. * <li>currentObject: The current Parse.Object being processed in the array.</li>
  937. * <li>index: The index of the current Parse.Object being processed in the array.</li>
  938. * <li>query: The query map was called upon.</li>
  939. * </ul>
  940. * @param {object} options Valid options are:<ul>
  941. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  942. * be used for this request.
  943. * <li>sessionToken: A valid session token, used for making a request on
  944. * behalf of a specific user.
  945. * </ul>
  946. * @returns {Promise} A promise that will be fulfilled once the
  947. * iteration has completed.
  948. */
  949. async map(callback, options) {
  950. const array = [];
  951. let index = 0;
  952. await this.each(object => {
  953. return Promise.resolve(callback(object, index, this)).then(result => {
  954. array.push(result);
  955. index += 1;
  956. });
  957. }, options);
  958. return array;
  959. }
  960. /**
  961. * Iterates over each result of a query, calling a callback for each one. If
  962. * the callback returns a promise, the iteration will not continue until
  963. * that promise has been fulfilled. If the callback returns a rejected
  964. * promise, then iteration will stop with that error. The items are
  965. * processed in an unspecified order. The query may not have any sort order,
  966. * and may not use limit or skip.
  967. *
  968. * @param {Function} callback Callback <ul>
  969. * <li>accumulator: The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback.</li>
  970. * <li>currentObject: The current Parse.Object being processed in the array.</li>
  971. * <li>index: The index of the current Parse.Object being processed in the array.</li>
  972. * </ul>
  973. * @param {*} initialValue A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first object in the query will be used and skipped.
  974. * @param {object} options Valid options are:<ul>
  975. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  976. * be used for this request.
  977. * <li>sessionToken: A valid session token, used for making a request on
  978. * behalf of a specific user.
  979. * </ul>
  980. * @returns {Promise} A promise that will be fulfilled once the
  981. * iteration has completed.
  982. */
  983. async reduce(callback, initialValue, options) {
  984. let accumulator = initialValue;
  985. let index = 0;
  986. await this.each(object => {
  987. // If no initial value was given, we take the first object from the query
  988. // as the initial value and don't call the callback with it.
  989. if (index === 0 && initialValue === undefined) {
  990. accumulator = object;
  991. index += 1;
  992. return;
  993. }
  994. return Promise.resolve(callback(accumulator, object, index)).then(result => {
  995. accumulator = result;
  996. index += 1;
  997. });
  998. }, options);
  999. if (index === 0 && initialValue === undefined) {
  1000. // Match Array.reduce behavior: "Calling reduce() on an empty array
  1001. // without an initialValue will throw a TypeError".
  1002. throw new TypeError('Reducing empty query result set with no initial value');
  1003. }
  1004. return accumulator;
  1005. }
  1006. /**
  1007. * Iterates over each result of a query, calling a callback for each one. If
  1008. * the callback returns a promise, the iteration will not continue until
  1009. * that promise has been fulfilled. If the callback returns a rejected
  1010. * promise, then iteration will stop with that error. The items are
  1011. * processed in an unspecified order. The query may not have any sort order,
  1012. * and may not use limit or skip.
  1013. *
  1014. * @param {Function} callback Callback <ul>
  1015. * <li>currentObject: The current Parse.Object being processed in the array.</li>
  1016. * <li>index: The index of the current Parse.Object being processed in the array.</li>
  1017. * <li>query: The query filter was called upon.</li>
  1018. * </ul>
  1019. * @param {object} options Valid options are:<ul>
  1020. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1021. * be used for this request.
  1022. * <li>sessionToken: A valid session token, used for making a request on
  1023. * behalf of a specific user.
  1024. * </ul>
  1025. * @returns {Promise} A promise that will be fulfilled once the
  1026. * iteration has completed.
  1027. */
  1028. async filter(callback, options) {
  1029. const array = [];
  1030. let index = 0;
  1031. await this.each(object => {
  1032. return Promise.resolve(callback(object, index, this)).then(flag => {
  1033. if (flag) {
  1034. array.push(object);
  1035. }
  1036. index += 1;
  1037. });
  1038. }, options);
  1039. return array;
  1040. }
  1041. /* Query Conditions */
  1042. /**
  1043. * Adds a constraint to the query that requires a particular key's value to
  1044. * be equal to the provided value.
  1045. *
  1046. * @param {string} key The key to check.
  1047. * @param value The value that the Parse.Object must contain.
  1048. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1049. */
  1050. equalTo(key, value) {
  1051. if (key && typeof key === 'object') {
  1052. Object.entries(key).forEach(([k, val]) => this.equalTo(k, val));
  1053. return this;
  1054. }
  1055. if (typeof value === 'undefined') {
  1056. return this.doesNotExist(key);
  1057. }
  1058. this._where[key] = (0, _encode.default)(value, false, true);
  1059. return this;
  1060. }
  1061. /**
  1062. * Adds a constraint to the query that requires a particular key's value to
  1063. * be not equal to the provided value.
  1064. *
  1065. * @param {string} key The key to check.
  1066. * @param value The value that must not be equalled.
  1067. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1068. */
  1069. notEqualTo(key, value) {
  1070. if (key && typeof key === 'object') {
  1071. Object.entries(key).forEach(([k, val]) => this.notEqualTo(k, val));
  1072. return this;
  1073. }
  1074. return this._addCondition(key, '$ne', value);
  1075. }
  1076. /**
  1077. * Adds a constraint to the query that requires a particular key's value to
  1078. * be less than the provided value.
  1079. *
  1080. * @param {string} key The key to check.
  1081. * @param value The value that provides an upper bound.
  1082. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1083. */
  1084. lessThan(key, value) {
  1085. return this._addCondition(key, '$lt', value);
  1086. }
  1087. /**
  1088. * Adds a constraint to the query that requires a particular key's value to
  1089. * be greater than the provided value.
  1090. *
  1091. * @param {string} key The key to check.
  1092. * @param value The value that provides an lower bound.
  1093. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1094. */
  1095. greaterThan(key, value) {
  1096. return this._addCondition(key, '$gt', value);
  1097. }
  1098. /**
  1099. * Adds a constraint to the query that requires a particular key's value to
  1100. * be less than or equal to the provided value.
  1101. *
  1102. * @param {string} key The key to check.
  1103. * @param value The value that provides an upper bound.
  1104. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1105. */
  1106. lessThanOrEqualTo(key, value) {
  1107. return this._addCondition(key, '$lte', value);
  1108. }
  1109. /**
  1110. * Adds a constraint to the query that requires a particular key's value to
  1111. * be greater than or equal to the provided value.
  1112. *
  1113. * @param {string} key The key to check.
  1114. * @param {*} value The value that provides an lower bound.
  1115. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1116. */
  1117. greaterThanOrEqualTo(key, value) {
  1118. return this._addCondition(key, '$gte', value);
  1119. }
  1120. /**
  1121. * Adds a constraint to the query that requires a particular key's value to
  1122. * be contained in the provided list of values.
  1123. *
  1124. * @param {string} key The key to check.
  1125. * @param {Array<*>} value The values that will match.
  1126. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1127. */
  1128. containedIn(key, value) {
  1129. return this._addCondition(key, '$in', value);
  1130. }
  1131. /**
  1132. * Adds a constraint to the query that requires a particular key's value to
  1133. * not be contained in the provided list of values.
  1134. *
  1135. * @param {string} key The key to check.
  1136. * @param {Array<*>} value The values that will not match.
  1137. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1138. */
  1139. notContainedIn(key, value) {
  1140. return this._addCondition(key, '$nin', value);
  1141. }
  1142. /**
  1143. * Adds a constraint to the query that requires a particular key's value to
  1144. * be contained by the provided list of values. Get objects where all array elements match.
  1145. *
  1146. * @param {string} key The key to check.
  1147. * @param {Array} values The values that will match.
  1148. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1149. */
  1150. containedBy(key, values) {
  1151. return this._addCondition(key, '$containedBy', values);
  1152. }
  1153. /**
  1154. * Adds a constraint to the query that requires a particular key's value to
  1155. * contain each one of the provided list of values.
  1156. *
  1157. * @param {string} key The key to check. This key's value must be an array.
  1158. * @param {Array} values The values that will match.
  1159. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1160. */
  1161. containsAll(key, values) {
  1162. return this._addCondition(key, '$all', values);
  1163. }
  1164. /**
  1165. * Adds a constraint to the query that requires a particular key's value to
  1166. * contain each one of the provided list of values starting with given strings.
  1167. *
  1168. * @param {string} key The key to check. This key's value must be an array.
  1169. * @param {Array<string>} values The string values that will match as starting string.
  1170. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1171. */
  1172. containsAllStartingWith(key, values) {
  1173. if (!Array.isArray(values)) {
  1174. values = [values];
  1175. }
  1176. const regexObject = values.map(value => {
  1177. return {
  1178. $regex: this._regexStartWith(value)
  1179. };
  1180. });
  1181. return this.containsAll(key, regexObject);
  1182. }
  1183. /**
  1184. * Adds a constraint for finding objects that contain the given key.
  1185. *
  1186. * @param {string} key The key that should exist.
  1187. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1188. */
  1189. exists(key) {
  1190. return this._addCondition(key, '$exists', true);
  1191. }
  1192. /**
  1193. * Adds a constraint for finding objects that do not contain a given key.
  1194. *
  1195. * @param {string} key The key that should not exist
  1196. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1197. */
  1198. doesNotExist(key) {
  1199. return this._addCondition(key, '$exists', false);
  1200. }
  1201. /**
  1202. * Adds a regular expression constraint for finding string values that match
  1203. * the provided regular expression.
  1204. * This may be slow for large datasets.
  1205. *
  1206. * @param {string} key The key that the string to match is stored in.
  1207. * @param {RegExp | string} regex The regular expression pattern to match.
  1208. * @param {string} modifiers The regular expression mode.
  1209. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1210. */
  1211. matches(key, regex, modifiers) {
  1212. this._addCondition(key, '$regex', regex);
  1213. if (!modifiers) {
  1214. modifiers = '';
  1215. }
  1216. if (typeof regex !== 'string') {
  1217. if (regex.ignoreCase) {
  1218. modifiers += 'i';
  1219. }
  1220. if (regex.multiline) {
  1221. modifiers += 'm';
  1222. }
  1223. }
  1224. if (modifiers.length) {
  1225. this._addCondition(key, '$options', modifiers);
  1226. }
  1227. return this;
  1228. }
  1229. /**
  1230. * Adds a constraint that requires that a key's value matches a Parse.Query
  1231. * constraint.
  1232. *
  1233. * @param {string} key The key that the contains the object to match the
  1234. * query.
  1235. * @param {Parse.Query} query The query that should match.
  1236. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1237. */
  1238. matchesQuery(key, query) {
  1239. const queryJSON = query.toJSON();
  1240. queryJSON.className = query.className;
  1241. return this._addCondition(key, '$inQuery', queryJSON);
  1242. }
  1243. /**
  1244. * Adds a constraint that requires that a key's value not matches a
  1245. * Parse.Query constraint.
  1246. *
  1247. * @param {string} key The key that the contains the object to match the
  1248. * query.
  1249. * @param {Parse.Query} query The query that should not match.
  1250. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1251. */
  1252. doesNotMatchQuery(key, query) {
  1253. const queryJSON = query.toJSON();
  1254. queryJSON.className = query.className;
  1255. return this._addCondition(key, '$notInQuery', queryJSON);
  1256. }
  1257. /**
  1258. * Adds a constraint that requires that a key's value matches a value in
  1259. * an object returned by a different Parse.Query.
  1260. *
  1261. * @param {string} key The key that contains the value that is being
  1262. * matched.
  1263. * @param {string} queryKey The key in the objects returned by the query to
  1264. * match against.
  1265. * @param {Parse.Query} query The query to run.
  1266. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1267. */
  1268. matchesKeyInQuery(key, queryKey, query) {
  1269. const queryJSON = query.toJSON();
  1270. queryJSON.className = query.className;
  1271. return this._addCondition(key, '$select', {
  1272. key: queryKey,
  1273. query: queryJSON
  1274. });
  1275. }
  1276. /**
  1277. * Adds a constraint that requires that a key's value not match a value in
  1278. * an object returned by a different Parse.Query.
  1279. *
  1280. * @param {string} key The key that contains the value that is being
  1281. * excluded.
  1282. * @param {string} queryKey The key in the objects returned by the query to
  1283. * match against.
  1284. * @param {Parse.Query} query The query to run.
  1285. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1286. */
  1287. doesNotMatchKeyInQuery(key, queryKey, query) {
  1288. const queryJSON = query.toJSON();
  1289. queryJSON.className = query.className;
  1290. return this._addCondition(key, '$dontSelect', {
  1291. key: queryKey,
  1292. query: queryJSON
  1293. });
  1294. }
  1295. /**
  1296. * Adds a constraint for finding string values that contain a provided
  1297. * string. This may be slow for large datasets.
  1298. *
  1299. * @param {string} key The key that the string to match is stored in.
  1300. * @param {string} substring The substring that the value must contain.
  1301. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1302. */
  1303. contains(key, substring) {
  1304. if (typeof substring !== 'string') {
  1305. throw new Error('The value being searched for must be a string.');
  1306. }
  1307. return this._addCondition(key, '$regex', quote(substring));
  1308. }
  1309. /**
  1310. * Adds a constraint for finding string values that contain a provided
  1311. * string. This may be slow for large datasets. Requires Parse-Server > 2.5.0
  1312. *
  1313. * In order to sort you must use select and ascending ($score is required)
  1314. * <pre>
  1315. * query.fullText('field', 'term');
  1316. * query.ascending('$score');
  1317. * query.select('$score');
  1318. * </pre>
  1319. *
  1320. * To retrieve the weight / rank
  1321. * <pre>
  1322. * object->get('score');
  1323. * </pre>
  1324. *
  1325. * You can define optionals by providing an object as a third parameter
  1326. * <pre>
  1327. * query.fullText('field', 'term', { language: 'es', diacriticSensitive: true });
  1328. * </pre>
  1329. *
  1330. * @param {string} key The key that the string to match is stored in.
  1331. * @param {string} value The string to search
  1332. * @param {object} options (Optional)
  1333. * @param {string} options.language The language that determines the list of stop words for the search and the rules for the stemmer and tokenizer.
  1334. * @param {boolean} options.caseSensitive A boolean flag to enable or disable case sensitive search.
  1335. * @param {boolean} options.diacriticSensitive A boolean flag to enable or disable diacritic sensitive search.
  1336. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1337. */
  1338. fullText(key, value, options = {}) {
  1339. options = options || {};
  1340. if (!key) {
  1341. throw new Error('A key is required.');
  1342. }
  1343. if (!value) {
  1344. throw new Error('A search term is required');
  1345. }
  1346. if (typeof value !== 'string') {
  1347. throw new Error('The value being searched for must be a string.');
  1348. }
  1349. const fullOptions = {};
  1350. fullOptions.$term = value;
  1351. for (const option in options) {
  1352. switch (option) {
  1353. case 'language':
  1354. fullOptions.$language = options[option];
  1355. break;
  1356. case 'caseSensitive':
  1357. fullOptions.$caseSensitive = options[option];
  1358. break;
  1359. case 'diacriticSensitive':
  1360. fullOptions.$diacriticSensitive = options[option];
  1361. break;
  1362. default:
  1363. throw new Error(`Unknown option: ${option}`);
  1364. }
  1365. }
  1366. return this._addCondition(key, '$text', {
  1367. $search: fullOptions
  1368. });
  1369. }
  1370. /**
  1371. * Method to sort the full text search by text score
  1372. *
  1373. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1374. */
  1375. sortByTextScore() {
  1376. this.ascending('$score');
  1377. this.select(['$score']);
  1378. return this;
  1379. }
  1380. /**
  1381. * Adds a constraint for finding string values that start with a provided
  1382. * string. This query will use the backend index, so it will be fast even
  1383. * for large datasets.
  1384. *
  1385. * @param {string} key The key that the string to match is stored in.
  1386. * @param {string} prefix The substring that the value must start with.
  1387. * @param {string} modifiers The regular expression mode.
  1388. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1389. */
  1390. startsWith(key, prefix, modifiers) {
  1391. if (typeof prefix !== 'string') {
  1392. throw new Error('The value being searched for must be a string.');
  1393. }
  1394. return this.matches(key, this._regexStartWith(prefix), modifiers);
  1395. }
  1396. /**
  1397. * Adds a constraint for finding string values that end with a provided
  1398. * string. This will be slow for large datasets.
  1399. *
  1400. * @param {string} key The key that the string to match is stored in.
  1401. * @param {string} suffix The substring that the value must end with.
  1402. * @param {string} modifiers The regular expression mode.
  1403. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1404. */
  1405. endsWith(key, suffix, modifiers) {
  1406. if (typeof suffix !== 'string') {
  1407. throw new Error('The value being searched for must be a string.');
  1408. }
  1409. return this.matches(key, quote(suffix) + '$', modifiers);
  1410. }
  1411. /**
  1412. * Adds a proximity based constraint for finding objects with key point
  1413. * values near the point given.
  1414. *
  1415. * @param {string} key The key that the Parse.GeoPoint is stored in.
  1416. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  1417. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1418. */
  1419. near(key, point) {
  1420. if (!(point instanceof _ParseGeoPoint.default)) {
  1421. // Try to cast it as a GeoPoint
  1422. point = new _ParseGeoPoint.default(point);
  1423. }
  1424. return this._addCondition(key, '$nearSphere', point);
  1425. }
  1426. /**
  1427. * Adds a proximity based constraint for finding objects with key point
  1428. * values near the point given and within the maximum distance given.
  1429. *
  1430. * @param {string} key The key that the Parse.GeoPoint is stored in.
  1431. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  1432. * @param {number} maxDistance Maximum distance (in radians) of results to return.
  1433. * @param {boolean} sorted A Bool value that is true if results should be
  1434. * sorted by distance ascending, false is no sorting is required,
  1435. * defaults to true.
  1436. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1437. */
  1438. withinRadians(key, point, maxDistance, sorted) {
  1439. if (sorted || sorted === undefined) {
  1440. this.near(key, point);
  1441. return this._addCondition(key, '$maxDistance', maxDistance);
  1442. } else {
  1443. return this._addCondition(key, '$geoWithin', {
  1444. $centerSphere: [[point.longitude, point.latitude], maxDistance]
  1445. });
  1446. }
  1447. }
  1448. /**
  1449. * Adds a proximity based constraint for finding objects with key point
  1450. * values near the point given and within the maximum distance given.
  1451. * Radius of earth used is 3958.8 miles.
  1452. *
  1453. * @param {string} key The key that the Parse.GeoPoint is stored in.
  1454. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  1455. * @param {number} maxDistance Maximum distance (in miles) of results to return.
  1456. * @param {boolean} sorted A Bool value that is true if results should be
  1457. * sorted by distance ascending, false is no sorting is required,
  1458. * defaults to true.
  1459. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1460. */
  1461. withinMiles(key, point, maxDistance, sorted) {
  1462. return this.withinRadians(key, point, maxDistance / 3958.8, sorted);
  1463. }
  1464. /**
  1465. * Adds a proximity based constraint for finding objects with key point
  1466. * values near the point given and within the maximum distance given.
  1467. * Radius of earth used is 6371.0 kilometers.
  1468. *
  1469. * @param {string} key The key that the Parse.GeoPoint is stored in.
  1470. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  1471. * @param {number} maxDistance Maximum distance (in kilometers) of results to return.
  1472. * @param {boolean} sorted A Bool value that is true if results should be
  1473. * sorted by distance ascending, false is no sorting is required,
  1474. * defaults to true.
  1475. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1476. */
  1477. withinKilometers(key, point, maxDistance, sorted) {
  1478. return this.withinRadians(key, point, maxDistance / 6371.0, sorted);
  1479. }
  1480. /**
  1481. * Adds a constraint to the query that requires a particular key's
  1482. * coordinates be contained within a given rectangular geographic bounding
  1483. * box.
  1484. *
  1485. * @param {string} key The key to be constrained.
  1486. * @param {Parse.GeoPoint} southwest
  1487. * The lower-left inclusive corner of the box.
  1488. * @param {Parse.GeoPoint} northeast
  1489. * The upper-right inclusive corner of the box.
  1490. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1491. */
  1492. withinGeoBox(key, southwest, northeast) {
  1493. if (!(southwest instanceof _ParseGeoPoint.default)) {
  1494. southwest = new _ParseGeoPoint.default(southwest);
  1495. }
  1496. if (!(northeast instanceof _ParseGeoPoint.default)) {
  1497. northeast = new _ParseGeoPoint.default(northeast);
  1498. }
  1499. this._addCondition(key, '$within', {
  1500. $box: [southwest, northeast]
  1501. });
  1502. return this;
  1503. }
  1504. /**
  1505. * Adds a constraint to the query that requires a particular key's
  1506. * coordinates be contained within and on the bounds of a given polygon.
  1507. * Supports closed and open (last point is connected to first) paths
  1508. *
  1509. * Polygon must have at least 3 points
  1510. *
  1511. * @param {string} key The key to be constrained.
  1512. * @param {Array} points Array of Coordinates / GeoPoints
  1513. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1514. */
  1515. withinPolygon(key, points) {
  1516. return this._addCondition(key, '$geoWithin', {
  1517. $polygon: points
  1518. });
  1519. }
  1520. /**
  1521. * Add a constraint to the query that requires a particular key's
  1522. * coordinates that contains a ParseGeoPoint
  1523. *
  1524. * @param {string} key The key to be constrained.
  1525. * @param {Parse.GeoPoint} point
  1526. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1527. */
  1528. polygonContains(key, point) {
  1529. return this._addCondition(key, '$geoIntersects', {
  1530. $point: point
  1531. });
  1532. }
  1533. /* Query Orderings */
  1534. /**
  1535. * Sorts the results in ascending order by the given key.
  1536. *
  1537. * @param {(string|string[])} keys The key to order by, which is a
  1538. * string of comma separated values, or an Array of keys, or multiple keys.
  1539. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1540. */
  1541. ascending(...keys) {
  1542. this._order = [];
  1543. return this.addAscending.apply(this, keys);
  1544. }
  1545. /**
  1546. * Sorts the results in ascending order by the given key,
  1547. * but can also add secondary sort descriptors without overwriting _order.
  1548. *
  1549. * @param {(string|string[])} keys The key to order by, which is a
  1550. * string of comma separated values, or an Array of keys, or multiple keys.
  1551. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1552. */
  1553. addAscending(...keys) {
  1554. if (!this._order) {
  1555. this._order = [];
  1556. }
  1557. keys.forEach(key => {
  1558. if (Array.isArray(key)) {
  1559. key = key.join();
  1560. }
  1561. this._order = this._order.concat(key.replace(/\s/g, '').split(','));
  1562. });
  1563. return this;
  1564. }
  1565. /**
  1566. * Sorts the results in descending order by the given key.
  1567. *
  1568. * @param {(string|string[])} keys The key to order by, which is a
  1569. * string of comma separated values, or an Array of keys, or multiple keys.
  1570. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1571. */
  1572. descending(...keys) {
  1573. this._order = [];
  1574. return this.addDescending.apply(this, keys);
  1575. }
  1576. /**
  1577. * Sorts the results in descending order by the given key,
  1578. * but can also add secondary sort descriptors without overwriting _order.
  1579. *
  1580. * @param {(string|string[])} keys The key to order by, which is a
  1581. * string of comma separated values, or an Array of keys, or multiple keys.
  1582. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1583. */
  1584. addDescending(...keys) {
  1585. if (!this._order) {
  1586. this._order = [];
  1587. }
  1588. keys.forEach(key => {
  1589. if (Array.isArray(key)) {
  1590. key = key.join();
  1591. }
  1592. this._order = this._order.concat(key.replace(/\s/g, '').split(',').map(k => {
  1593. return '-' + k;
  1594. }));
  1595. });
  1596. return this;
  1597. }
  1598. /* Query Options */
  1599. /**
  1600. * Sets the number of results to skip before returning any results.
  1601. * This is useful for pagination.
  1602. * Default is to skip zero results.
  1603. *
  1604. * @param {number} n the number of results to skip.
  1605. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1606. */
  1607. skip(n) {
  1608. if (typeof n !== 'number' || n < 0) {
  1609. throw new Error('You can only skip by a positive number');
  1610. }
  1611. this._skip = n;
  1612. return this;
  1613. }
  1614. /**
  1615. * Sets the limit of the number of results to return. The default limit is 100.
  1616. *
  1617. * @param {number} n the number of results to limit to.
  1618. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1619. */
  1620. limit(n) {
  1621. if (typeof n !== 'number') {
  1622. throw new Error('You can only set the limit to a numeric value');
  1623. }
  1624. this._limit = n;
  1625. return this;
  1626. }
  1627. /**
  1628. * Sets the flag to include with response the total number of objects satisfying this query,
  1629. * despite limits/skip. Might be useful for pagination.
  1630. * Note that result of this query will be wrapped as an object with
  1631. * `results`: holding {ParseObject} array and `count`: integer holding total number
  1632. *
  1633. * @param {boolean} includeCount false - disable, true - enable.
  1634. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1635. */
  1636. withCount(includeCount = true) {
  1637. if (typeof includeCount !== 'boolean') {
  1638. throw new Error('You can only set withCount to a boolean value');
  1639. }
  1640. this._count = includeCount;
  1641. return this;
  1642. }
  1643. /**
  1644. * Includes nested Parse.Objects for the provided key. You can use dot
  1645. * notation to specify which fields in the included object are also fetched.
  1646. *
  1647. * You can include all nested Parse.Objects by passing in '*'.
  1648. * Requires Parse Server 3.0.0+
  1649. * <pre>query.include('*');</pre>
  1650. *
  1651. * @param {...string|Array<string>} keys The name(s) of the key(s) to include.
  1652. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1653. */
  1654. include(...keys) {
  1655. keys.forEach(key => {
  1656. if (Array.isArray(key)) {
  1657. this._include = this._include.concat(key);
  1658. } else {
  1659. this._include.push(key);
  1660. }
  1661. });
  1662. return this;
  1663. }
  1664. /**
  1665. * Includes all nested Parse.Objects one level deep.
  1666. *
  1667. * Requires Parse Server 3.0.0+
  1668. *
  1669. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1670. */
  1671. includeAll() {
  1672. return this.include('*');
  1673. }
  1674. /**
  1675. * Restricts the fields of the returned Parse.Objects to include only the
  1676. * provided keys. If this is called multiple times, then all of the keys
  1677. * specified in each of the calls will be included.
  1678. *
  1679. * @param {...string|Array<string>} keys The name(s) of the key(s) to include.
  1680. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1681. */
  1682. select(...keys) {
  1683. if (!this._select) {
  1684. this._select = [];
  1685. }
  1686. keys.forEach(key => {
  1687. if (Array.isArray(key)) {
  1688. this._select = this._select.concat(key);
  1689. } else {
  1690. this._select.push(key);
  1691. }
  1692. });
  1693. return this;
  1694. }
  1695. /**
  1696. * Restricts the fields of the returned Parse.Objects to all keys except the
  1697. * provided keys. Exclude takes precedence over select and include.
  1698. *
  1699. * Requires Parse Server 3.6.0+
  1700. *
  1701. * @param {...string|Array<string>} keys The name(s) of the key(s) to exclude.
  1702. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1703. */
  1704. exclude(...keys) {
  1705. keys.forEach(key => {
  1706. if (Array.isArray(key)) {
  1707. this._exclude = this._exclude.concat(key);
  1708. } else {
  1709. this._exclude.push(key);
  1710. }
  1711. });
  1712. return this;
  1713. }
  1714. /**
  1715. * Restricts live query to trigger only for watched fields.
  1716. *
  1717. * Requires Parse Server 6.0.0+
  1718. *
  1719. * @param {...string|Array<string>} keys The name(s) of the key(s) to watch.
  1720. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1721. */
  1722. watch(...keys) {
  1723. keys.forEach(key => {
  1724. if (Array.isArray(key)) {
  1725. this._watch = this._watch.concat(key);
  1726. } else {
  1727. this._watch.push(key);
  1728. }
  1729. });
  1730. return this;
  1731. }
  1732. /**
  1733. * Changes the read preference that the backend will use when performing the query to the database.
  1734. *
  1735. * @param {string} readPreference The read preference for the main query.
  1736. * @param {string} includeReadPreference The read preference for the queries to include pointers.
  1737. * @param {string} subqueryReadPreference The read preference for the sub queries.
  1738. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1739. */
  1740. readPreference(readPreference, includeReadPreference, subqueryReadPreference) {
  1741. this._readPreference = readPreference;
  1742. this._includeReadPreference = includeReadPreference || null;
  1743. this._subqueryReadPreference = subqueryReadPreference || null;
  1744. return this;
  1745. }
  1746. /**
  1747. * Subscribe this query to get liveQuery updates
  1748. *
  1749. * @param {string} sessionToken (optional) Defaults to the currentUser
  1750. * @returns {Promise<LiveQuerySubscription>} Returns the liveQuerySubscription, it's an event emitter
  1751. * which can be used to get liveQuery updates.
  1752. */
  1753. async subscribe(sessionToken) {
  1754. const currentUser = await _CoreManager.default.getUserController().currentUserAsync();
  1755. if (!sessionToken) {
  1756. sessionToken = currentUser ? currentUser.getSessionToken() || undefined : undefined;
  1757. }
  1758. const liveQueryClient = await _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient();
  1759. if (liveQueryClient.shouldOpen()) {
  1760. liveQueryClient.open();
  1761. }
  1762. const subscription = liveQueryClient.subscribe(this, sessionToken);
  1763. return subscription.subscribePromise.then(() => {
  1764. return subscription;
  1765. });
  1766. }
  1767. /**
  1768. * Constructs a Parse.Query that is the OR of the passed in queries. For
  1769. * example:
  1770. * <pre>var compoundQuery = Parse.Query.or(query1, query2, query3);</pre>
  1771. *
  1772. * will create a compoundQuery that is an or of the query1, query2, and
  1773. * query3.
  1774. *
  1775. * @param {...Parse.Query} queries The list of queries to OR.
  1776. * @static
  1777. * @returns {Parse.Query} The query that is the OR of the passed in queries.
  1778. */
  1779. static or(...queries) {
  1780. const className = _getClassNameFromQueries(queries);
  1781. const query = new ParseQuery(className);
  1782. query._orQuery(queries);
  1783. return query;
  1784. }
  1785. /**
  1786. * Constructs a Parse.Query that is the AND of the passed in queries. For
  1787. * example:
  1788. * <pre>var compoundQuery = Parse.Query.and(query1, query2, query3);</pre>
  1789. *
  1790. * will create a compoundQuery that is an and of the query1, query2, and
  1791. * query3.
  1792. *
  1793. * @param {...Parse.Query} queries The list of queries to AND.
  1794. * @static
  1795. * @returns {Parse.Query} The query that is the AND of the passed in queries.
  1796. */
  1797. static and(...queries) {
  1798. const className = _getClassNameFromQueries(queries);
  1799. const query = new ParseQuery(className);
  1800. query._andQuery(queries);
  1801. return query;
  1802. }
  1803. /**
  1804. * Constructs a Parse.Query that is the NOR of the passed in queries. For
  1805. * example:
  1806. * <pre>const compoundQuery = Parse.Query.nor(query1, query2, query3);</pre>
  1807. *
  1808. * will create a compoundQuery that is a nor of the query1, query2, and
  1809. * query3.
  1810. *
  1811. * @param {...Parse.Query} queries The list of queries to NOR.
  1812. * @static
  1813. * @returns {Parse.Query} The query that is the NOR of the passed in queries.
  1814. */
  1815. static nor(...queries) {
  1816. const className = _getClassNameFromQueries(queries);
  1817. const query = new ParseQuery(className);
  1818. query._norQuery(queries);
  1819. return query;
  1820. }
  1821. /**
  1822. * Change the source of this query to the server.
  1823. *
  1824. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1825. */
  1826. fromNetwork() {
  1827. this._queriesLocalDatastore = false;
  1828. this._localDatastorePinName = null;
  1829. return this;
  1830. }
  1831. /**
  1832. * Changes the source of this query to all pinned objects.
  1833. *
  1834. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1835. */
  1836. fromLocalDatastore() {
  1837. return this.fromPinWithName(null);
  1838. }
  1839. /**
  1840. * Changes the source of this query to the default group of pinned objects.
  1841. *
  1842. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1843. */
  1844. fromPin() {
  1845. return this.fromPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
  1846. }
  1847. /**
  1848. * Changes the source of this query to a specific group of pinned objects.
  1849. *
  1850. * @param {string} name The name of query source.
  1851. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1852. */
  1853. fromPinWithName(name) {
  1854. const localDatastore = _CoreManager.default.getLocalDatastore();
  1855. if (localDatastore.checkIfEnabled()) {
  1856. this._queriesLocalDatastore = true;
  1857. this._localDatastorePinName = name;
  1858. }
  1859. return this;
  1860. }
  1861. /**
  1862. * Cancels the current network request (if any is running).
  1863. *
  1864. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1865. */
  1866. cancel() {
  1867. if (this._xhrRequest.task && typeof this._xhrRequest.task.abort === 'function') {
  1868. this._xhrRequest.task._aborted = true;
  1869. this._xhrRequest.task.abort();
  1870. this._xhrRequest.task = null;
  1871. this._xhrRequest.onchange = () => {};
  1872. return this;
  1873. }
  1874. this._xhrRequest.onchange = () => this.cancel();
  1875. return this;
  1876. }
  1877. _setRequestTask(options) {
  1878. options.requestTask = task => {
  1879. this._xhrRequest.task = task;
  1880. this._xhrRequest.onchange();
  1881. };
  1882. }
  1883. /**
  1884. * Sets a comment to the query so that the query
  1885. * can be identified when using a the profiler for MongoDB.
  1886. *
  1887. * @param {string} value a comment can make your profile data easier to interpret and trace.
  1888. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1889. */
  1890. comment(value) {
  1891. if (value == null) {
  1892. delete this._comment;
  1893. return this;
  1894. }
  1895. if (typeof value !== 'string') {
  1896. throw new Error('The value of a comment to be sent with this query must be a string.');
  1897. }
  1898. this._comment = value;
  1899. return this;
  1900. }
  1901. }
  1902. const DefaultController = {
  1903. find(className, params, options) {
  1904. const RESTController = _CoreManager.default.getRESTController();
  1905. return RESTController.request('GET', 'classes/' + className, params, options);
  1906. },
  1907. aggregate(className, params, options) {
  1908. const RESTController = _CoreManager.default.getRESTController();
  1909. return RESTController.request('GET', 'aggregate/' + className, params, options);
  1910. }
  1911. };
  1912. _CoreManager.default.setParseQuery(ParseQuery);
  1913. _CoreManager.default.setQueryController(DefaultController);
  1914. var _default = exports.default = ParseQuery;