ParseQuery.js 73 KB

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