ParseQuery.js 71 KB

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