ParseQuery.js 58 KB

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