ParseQuery.js 58 KB

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