ParseQuery.js 69 KB

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