ParseQuery.js 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093
  1. "use strict";
  2. var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
  3. var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
  4. _Object$defineProperty(exports, "__esModule", {
  5. value: true
  6. });
  7. exports.default = void 0;
  8. var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs3/regenerator"));
  9. var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/slicedToArray"));
  10. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray"));
  11. var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator"));
  12. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/classCallCheck"));
  13. var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/createClass"));
  14. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));
  15. var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof"));
  16. var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
  17. var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
  18. var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));
  19. var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
  20. var _map2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));
  21. var _filter2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));
  22. var _keys2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/keys"));
  23. var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));
  24. var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/includes"));
  25. var _sort = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/sort"));
  26. var _splice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/splice"));
  27. var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));
  28. var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find"));
  29. var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array"));
  30. var _entries = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/entries"));
  31. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  32. var _encode = _interopRequireDefault(require("./encode"));
  33. var _promiseUtils = require("./promiseUtils");
  34. var _ParseError = _interopRequireDefault(require("./ParseError"));
  35. var _ParseGeoPoint = _interopRequireDefault(require("./ParseGeoPoint"));
  36. var _ParseObject = _interopRequireDefault(require("./ParseObject"));
  37. var _OfflineQuery = _interopRequireDefault(require("./OfflineQuery"));
  38. var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
  39. /*
  40. * Copyright (c) 2015-present, Parse, LLC.
  41. * All rights reserved.
  42. *
  43. * This source code is licensed under the BSD-style license found in the
  44. * LICENSE file in the root directory of this source tree. An additional grant
  45. * of patent rights can be found in the PATENTS file in the same directory.
  46. *
  47. * @flow
  48. */
  49. /**
  50. * Converts a string into a regex that matches it.
  51. * Surrounding with \Q .. \E does this, we just need to escape any \E's in
  52. * the text separately.
  53. *
  54. * @param s
  55. * @private
  56. * @returns {string}
  57. */
  58. function quote(s
  59. /*: string*/
  60. )
  61. /*: string*/
  62. {
  63. return "\\Q".concat(s.replace('\\E', '\\E\\\\E\\Q'), "\\E");
  64. }
  65. /**
  66. * Extracts the class name from queries. If not all queries have the same
  67. * class name an error will be thrown.
  68. *
  69. * @param queries
  70. * @private
  71. * @returns {string}
  72. */
  73. function _getClassNameFromQueries(queries
  74. /*: Array<ParseQuery>*/
  75. )
  76. /*: ?string*/
  77. {
  78. var className = null;
  79. (0, _forEach.default)(queries).call(queries, function (q) {
  80. if (!className) {
  81. // eslint-disable-next-line prefer-destructuring
  82. className = q.className;
  83. }
  84. if (className !== q.className) {
  85. throw new Error('All queries must be for the same class.');
  86. }
  87. });
  88. return className;
  89. }
  90. /*
  91. * Handles pre-populating the result data of a query with select fields,
  92. * making sure that the data object contains keys for all objects that have
  93. * been requested with a select, so that our cached state updates correctly.
  94. */
  95. function handleSelectResult(data
  96. /*: any*/
  97. , select
  98. /*: Array<string>*/
  99. ) {
  100. var serverDataMask = {};
  101. (0, _forEach.default)(select).call(select, function (field) {
  102. var hasSubObjectSelect = (0, _indexOf.default)(field).call(field, '.') !== -1;
  103. if (!hasSubObjectSelect && !data.hasOwnProperty(field)) {
  104. // this field was selected, but is missing from the retrieved data
  105. data[field] = undefined;
  106. } else if (hasSubObjectSelect) {
  107. // this field references a sub-object,
  108. // so we need to walk down the path components
  109. var pathComponents = field.split('.');
  110. var _obj = data;
  111. var serverMask = serverDataMask;
  112. (0, _forEach.default)(pathComponents).call(pathComponents, function (component, index, arr) {
  113. // add keys if the expected data is missing
  114. if (_obj && !_obj.hasOwnProperty(component)) {
  115. _obj[component] = undefined;
  116. }
  117. if (_obj && (0, _typeof2.default)(_obj) === 'object') {
  118. _obj = _obj[component];
  119. } // add this path component to the server mask so we can fill it in later if needed
  120. if (index < arr.length - 1) {
  121. if (!serverMask[component]) {
  122. serverMask[component] = {};
  123. }
  124. serverMask = serverMask[component];
  125. }
  126. });
  127. }
  128. });
  129. if ((0, _keys.default)(serverDataMask).length > 0) {
  130. // When selecting from sub-objects, we don't want to blow away the missing
  131. // information that we may have retrieved before. We've already added any
  132. // missing selected keys to sub-objects, but we still need to add in the
  133. // data for any previously retrieved sub-objects that were not selected.
  134. var serverData = _CoreManager.default.getObjectStateController().getServerData({
  135. id: data.objectId,
  136. className: data.className
  137. });
  138. copyMissingDataWithMask(serverData, data, serverDataMask, false);
  139. }
  140. }
  141. function copyMissingDataWithMask(src, dest, mask, copyThisLevel) {
  142. // copy missing elements at this level
  143. if (copyThisLevel) {
  144. for (var _key in src) {
  145. if (src.hasOwnProperty(_key) && !dest.hasOwnProperty(_key)) {
  146. dest[_key] = src[_key];
  147. }
  148. }
  149. }
  150. for (var _key2 in mask) {
  151. if (dest[_key2] !== undefined && dest[_key2] !== null && src !== undefined && src !== null) {
  152. // traverse into objects as needed
  153. copyMissingDataWithMask(src[_key2], dest[_key2], mask[_key2], true);
  154. }
  155. }
  156. }
  157. function handleOfflineSort(a, b, sorts) {
  158. var order = sorts[0];
  159. var operator = (0, _slice.default)(order).call(order, 0, 1);
  160. var isDescending = operator === '-';
  161. if (isDescending) {
  162. order = order.substring(1);
  163. }
  164. if (order === '_created_at') {
  165. order = 'createdAt';
  166. }
  167. if (order === '_updated_at') {
  168. order = 'updatedAt';
  169. }
  170. if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(order) || order === 'password') {
  171. throw new _ParseError.default(_ParseError.default.INVALID_KEY_NAME, "Invalid Key: ".concat(order));
  172. }
  173. var field1 = a.get(order);
  174. var field2 = b.get(order);
  175. if (field1 < field2) {
  176. return isDescending ? 1 : -1;
  177. }
  178. if (field1 > field2) {
  179. return isDescending ? -1 : 1;
  180. }
  181. if (sorts.length > 1) {
  182. var remainingSorts = (0, _slice.default)(sorts).call(sorts, 1);
  183. return handleOfflineSort(a, b, remainingSorts);
  184. }
  185. return 0;
  186. }
  187. /**
  188. * Creates a new parse Parse.Query for the given Parse.Object subclass.
  189. *
  190. * <p>Parse.Query defines a query that is used to fetch Parse.Objects. The
  191. * most common use case is finding all objects that match a query through the
  192. * <code>find</code> method. for example, this sample code fetches all objects
  193. * of class <code>myclass</code>. it calls a different function depending on
  194. * whether the fetch succeeded or not.
  195. *
  196. * <pre>
  197. * var query = new Parse.Query(myclass);
  198. * query.find().then((results) => {
  199. * // results is an array of parse.object.
  200. * }).catch((error) => {
  201. * // error is an instance of parse.error.
  202. * });</pre></p>
  203. *
  204. * <p>a Parse.Query can also be used to retrieve a single object whose id is
  205. * known, through the get method. for example, this sample code fetches an
  206. * object of class <code>myclass</code> and id <code>myid</code>. it calls a
  207. * different function depending on whether the fetch succeeded or not.
  208. *
  209. * <pre>
  210. * var query = new Parse.Query(myclass);
  211. * query.get(myid).then((object) => {
  212. * // object is an instance of parse.object.
  213. * }).catch((error) => {
  214. * // error is an instance of parse.error.
  215. * });</pre></p>
  216. *
  217. * <p>a Parse.Query can also be used to count the number of objects that match
  218. * the query without retrieving all of those objects. for example, this
  219. * sample code counts the number of objects of the class <code>myclass</code>
  220. * <pre>
  221. * var query = new Parse.Query(myclass);
  222. * query.count().then((number) => {
  223. * // there are number instances of myclass.
  224. * }).catch((error) => {
  225. * // error is an instance of Parse.Error.
  226. * });</pre></p>
  227. *
  228. * @alias Parse.Query
  229. */
  230. var ParseQuery = /*#__PURE__*/function () {
  231. /**
  232. * @property {string} className
  233. */
  234. /**
  235. * @param {(string | Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string.
  236. */
  237. function ParseQuery(objectClass
  238. /*: string | ParseObject*/
  239. ) {
  240. (0, _classCallCheck2.default)(this, ParseQuery);
  241. (0, _defineProperty2.default)(this, "className", void 0);
  242. (0, _defineProperty2.default)(this, "_where", void 0);
  243. (0, _defineProperty2.default)(this, "_include", void 0);
  244. (0, _defineProperty2.default)(this, "_exclude", void 0);
  245. (0, _defineProperty2.default)(this, "_select", void 0);
  246. (0, _defineProperty2.default)(this, "_limit", void 0);
  247. (0, _defineProperty2.default)(this, "_skip", void 0);
  248. (0, _defineProperty2.default)(this, "_count", void 0);
  249. (0, _defineProperty2.default)(this, "_order", void 0);
  250. (0, _defineProperty2.default)(this, "_readPreference", void 0);
  251. (0, _defineProperty2.default)(this, "_includeReadPreference", void 0);
  252. (0, _defineProperty2.default)(this, "_subqueryReadPreference", void 0);
  253. (0, _defineProperty2.default)(this, "_queriesLocalDatastore", void 0);
  254. (0, _defineProperty2.default)(this, "_localDatastorePinName", void 0);
  255. (0, _defineProperty2.default)(this, "_extraOptions", void 0);
  256. (0, _defineProperty2.default)(this, "_hint", void 0);
  257. (0, _defineProperty2.default)(this, "_explain", void 0);
  258. (0, _defineProperty2.default)(this, "_xhrRequest", void 0);
  259. if (typeof objectClass === 'string') {
  260. if (objectClass === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  261. this.className = '_User';
  262. } else {
  263. this.className = objectClass;
  264. }
  265. } else if (objectClass instanceof _ParseObject.default) {
  266. this.className = objectClass.className;
  267. } else if (typeof objectClass === 'function') {
  268. if (typeof objectClass.className === 'string') {
  269. this.className = objectClass.className;
  270. } else {
  271. var _obj2 = new objectClass();
  272. this.className = _obj2.className;
  273. }
  274. } else {
  275. throw new TypeError('A ParseQuery must be constructed with a ParseObject or class name.');
  276. }
  277. this._where = {};
  278. this._include = [];
  279. this._exclude = [];
  280. this._count = false; // negative limit is not sent in the server request
  281. this._limit = -1;
  282. this._skip = 0;
  283. this._readPreference = null;
  284. this._includeReadPreference = null;
  285. this._subqueryReadPreference = null;
  286. this._queriesLocalDatastore = false;
  287. this._localDatastorePinName = null;
  288. this._extraOptions = {};
  289. this._xhrRequest = {
  290. task: null,
  291. onchange: function () {}
  292. };
  293. }
  294. /**
  295. * Adds constraint that at least one of the passed in queries matches.
  296. *
  297. * @param {Array} queries
  298. * @returns {Parse.Query} Returns the query, so you can chain this call.
  299. */
  300. (0, _createClass2.default)(ParseQuery, [{
  301. key: "_orQuery",
  302. value: function (queries
  303. /*: Array<ParseQuery>*/
  304. )
  305. /*: ParseQuery*/
  306. {
  307. var queryJSON = (0, _map2.default)(queries).call(queries, function (q) {
  308. return q.toJSON().where;
  309. });
  310. this._where.$or = queryJSON;
  311. return this;
  312. }
  313. /**
  314. * Adds constraint that all of the passed in queries match.
  315. *
  316. * @param {Array} queries
  317. * @returns {Parse.Query} Returns the query, so you can chain this call.
  318. */
  319. }, {
  320. key: "_andQuery",
  321. value: function (queries
  322. /*: Array<ParseQuery>*/
  323. )
  324. /*: ParseQuery*/
  325. {
  326. var queryJSON = (0, _map2.default)(queries).call(queries, function (q) {
  327. return q.toJSON().where;
  328. });
  329. this._where.$and = queryJSON;
  330. return this;
  331. }
  332. /**
  333. * Adds constraint that none of the passed in queries match.
  334. *
  335. * @param {Array} queries
  336. * @returns {Parse.Query} Returns the query, so you can chain this call.
  337. */
  338. }, {
  339. key: "_norQuery",
  340. value: function (queries
  341. /*: Array<ParseQuery>*/
  342. )
  343. /*: ParseQuery*/
  344. {
  345. var queryJSON = (0, _map2.default)(queries).call(queries, function (q) {
  346. return q.toJSON().where;
  347. });
  348. this._where.$nor = queryJSON;
  349. return this;
  350. }
  351. /**
  352. * Helper for condition queries
  353. *
  354. * @param key
  355. * @param condition
  356. * @param value
  357. * @returns {Parse.Query}
  358. */
  359. }, {
  360. key: "_addCondition",
  361. value: function (key
  362. /*: string*/
  363. , condition
  364. /*: string*/
  365. , value
  366. /*: mixed*/
  367. )
  368. /*: ParseQuery*/
  369. {
  370. if (!this._where[key] || typeof this._where[key] === 'string') {
  371. this._where[key] = {};
  372. }
  373. this._where[key][condition] = (0, _encode.default)(value, false, true);
  374. return this;
  375. }
  376. /**
  377. * Converts string for regular expression at the beginning
  378. *
  379. * @param string
  380. * @returns {string}
  381. */
  382. }, {
  383. key: "_regexStartWith",
  384. value: function (string
  385. /*: string*/
  386. )
  387. /*: string*/
  388. {
  389. return "^".concat(quote(string));
  390. }
  391. }, {
  392. key: "_handleOfflineQuery",
  393. value: function () {
  394. var _handleOfflineQuery2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(params
  395. /*: any*/
  396. ) {
  397. var _context,
  398. _this2 = this;
  399. var localDatastore, objects, results, keys, alwaysSelectedKeys, sorts, count, limit;
  400. return _regenerator.default.wrap(function (_context3) {
  401. while (1) {
  402. switch (_context3.prev = _context3.next) {
  403. case 0:
  404. _OfflineQuery.default.validateQuery(this);
  405. localDatastore = _CoreManager.default.getLocalDatastore();
  406. _context3.next = 4;
  407. return localDatastore._serializeObjectsFromPinName(this._localDatastorePinName);
  408. case 4:
  409. objects = _context3.sent;
  410. results = (0, _filter2.default)(_context = (0, _map2.default)(objects).call(objects, function (json, index, arr) {
  411. var object = _ParseObject.default.fromJSON(json, false);
  412. if (json._localId && !json.objectId) {
  413. object._localId = json._localId;
  414. }
  415. if (!_OfflineQuery.default.matchesQuery(_this2.className, object, arr, _this2)) {
  416. return null;
  417. }
  418. return object;
  419. })).call(_context, function (object) {
  420. return object !== null;
  421. });
  422. if ((0, _keys2.default)(params)) {
  423. keys = (0, _keys2.default)(params).split(',');
  424. alwaysSelectedKeys = ['className', 'objectId', 'createdAt', 'updatedAt', 'ACL'];
  425. keys = (0, _concat.default)(keys).call(keys, alwaysSelectedKeys);
  426. results = (0, _map2.default)(results).call(results, function (object) {
  427. var _context2;
  428. var json = object._toFullJSON();
  429. (0, _forEach.default)(_context2 = (0, _keys.default)(json)).call(_context2, function (key) {
  430. if (!(0, _includes.default)(keys).call(keys, key)) {
  431. delete json[key];
  432. }
  433. });
  434. return _ParseObject.default.fromJSON(json, false);
  435. });
  436. }
  437. if (params.order) {
  438. sorts = params.order.split(',');
  439. (0, _sort.default)(results).call(results, function (a, b) {
  440. return handleOfflineSort(a, b, sorts);
  441. });
  442. } // count total before applying limit/skip
  443. if (params.count) {
  444. // total count from response
  445. count = results.length;
  446. }
  447. if (params.skip) {
  448. if (params.skip >= results.length) {
  449. results = [];
  450. } else {
  451. results = (0, _splice.default)(results).call(results, params.skip, results.length);
  452. }
  453. }
  454. limit = results.length;
  455. if (params.limit !== 0 && params.limit < results.length) {
  456. // eslint-disable-next-line prefer-destructuring
  457. limit = params.limit;
  458. }
  459. results = (0, _splice.default)(results).call(results, 0, limit);
  460. if (!(typeof count === 'number')) {
  461. _context3.next = 15;
  462. break;
  463. }
  464. return _context3.abrupt("return", {
  465. results: results,
  466. count: count
  467. });
  468. case 15:
  469. return _context3.abrupt("return", results);
  470. case 16:
  471. case "end":
  472. return _context3.stop();
  473. }
  474. }
  475. }, _callee, this);
  476. }));
  477. return function () {
  478. return _handleOfflineQuery2.apply(this, arguments);
  479. };
  480. }()
  481. /**
  482. * Returns a JSON representation of this query.
  483. *
  484. * @returns {object} The JSON representation of the query.
  485. */
  486. }, {
  487. key: "toJSON",
  488. value: function ()
  489. /*: QueryJSON*/
  490. {
  491. var params
  492. /*: QueryJSON*/
  493. = {
  494. where: this._where
  495. };
  496. if (this._include.length) {
  497. params.include = this._include.join(',');
  498. }
  499. if (this._exclude.length) {
  500. params.excludeKeys = this._exclude.join(',');
  501. }
  502. if (this._select) {
  503. params.keys = this._select.join(',');
  504. }
  505. if (this._count) {
  506. params.count = 1;
  507. }
  508. if (this._limit >= 0) {
  509. params.limit = this._limit;
  510. }
  511. if (this._skip > 0) {
  512. params.skip = this._skip;
  513. }
  514. if (this._order) {
  515. params.order = this._order.join(',');
  516. }
  517. if (this._readPreference) {
  518. params.readPreference = this._readPreference;
  519. }
  520. if (this._includeReadPreference) {
  521. params.includeReadPreference = this._includeReadPreference;
  522. }
  523. if (this._subqueryReadPreference) {
  524. params.subqueryReadPreference = this._subqueryReadPreference;
  525. }
  526. if (this._hint) {
  527. params.hint = this._hint;
  528. }
  529. if (this._explain) {
  530. params.explain = true;
  531. }
  532. for (var _key3 in this._extraOptions) {
  533. params[_key3] = this._extraOptions[_key3];
  534. }
  535. return params;
  536. }
  537. /**
  538. * Return a query with conditions from json, can be useful to send query from server side to client
  539. * Not static, all query conditions was set before calling this method will be deleted.
  540. * For example on the server side we have
  541. * var query = new Parse.Query("className");
  542. * query.equalTo(key: value);
  543. * query.limit(100);
  544. * ... (others queries)
  545. * Create JSON representation of Query Object
  546. * var jsonFromServer = query.fromJSON();
  547. *
  548. * On client side getting query:
  549. * var query = new Parse.Query("className");
  550. * query.fromJSON(jsonFromServer);
  551. *
  552. * and continue to query...
  553. * query.skip(100).find().then(...);
  554. *
  555. * @param {QueryJSON} json from Parse.Query.toJSON() method
  556. * @returns {Parse.Query} Returns the query, so you can chain this call.
  557. */
  558. }, {
  559. key: "withJSON",
  560. value: function (json
  561. /*: QueryJSON*/
  562. )
  563. /*: ParseQuery*/
  564. {
  565. if (json.where) {
  566. this._where = json.where;
  567. }
  568. if (json.include) {
  569. this._include = json.include.split(',');
  570. }
  571. if ((0, _keys2.default)(json)) {
  572. this._select = (0, _keys2.default)(json).split(',');
  573. }
  574. if (json.excludeKeys) {
  575. this._exclude = json.excludeKeys.split(',');
  576. }
  577. if (json.count) {
  578. this._count = json.count === 1;
  579. }
  580. if (json.limit) {
  581. this._limit = json.limit;
  582. }
  583. if (json.skip) {
  584. this._skip = json.skip;
  585. }
  586. if (json.order) {
  587. this._order = json.order.split(',');
  588. }
  589. if (json.readPreference) {
  590. this._readPreference = json.readPreference;
  591. }
  592. if (json.includeReadPreference) {
  593. this._includeReadPreference = json.includeReadPreference;
  594. }
  595. if (json.subqueryReadPreference) {
  596. this._subqueryReadPreference = json.subqueryReadPreference;
  597. }
  598. if (json.hint) {
  599. this._hint = json.hint;
  600. }
  601. if (json.explain) {
  602. this._explain = !!json.explain;
  603. }
  604. for (var _key4 in json) {
  605. if (json.hasOwnProperty(_key4)) {
  606. var _context4;
  607. if ((0, _indexOf.default)(_context4 = ['where', 'include', 'keys', 'count', 'limit', 'skip', 'order', 'readPreference', 'includeReadPreference', 'subqueryReadPreference', 'hint', 'explain']).call(_context4, _key4) === -1) {
  608. this._extraOptions[_key4] = json[_key4];
  609. }
  610. }
  611. }
  612. return this;
  613. }
  614. /**
  615. * Static method to restore Parse.Query by json representation
  616. * Internally calling Parse.Query.withJSON
  617. *
  618. * @param {string} className
  619. * @param {QueryJSON} json from Parse.Query.toJSON() method
  620. * @returns {Parse.Query} new created query
  621. */
  622. }, {
  623. key: "get",
  624. value:
  625. /**
  626. * Constructs a Parse.Object whose id is already known by fetching data from
  627. * the server. Unlike the <code>first</code> method, it never returns undefined.
  628. *
  629. * @param {string} objectId The id of the object to be fetched.
  630. * @param {object} options
  631. * Valid options are:<ul>
  632. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  633. * be used for this request.
  634. * <li>sessionToken: A valid session token, used for making a request on
  635. * behalf of a specific user.
  636. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  637. * </ul>
  638. *
  639. * @returns {Promise} A promise that is resolved with the result when
  640. * the query completes.
  641. */
  642. function (objectId
  643. /*: string*/
  644. , options
  645. /*:: ?: FullOptions*/
  646. )
  647. /*: Promise<ParseObject>*/
  648. {
  649. this.equalTo('objectId', objectId);
  650. var firstOptions = {};
  651. if (options && options.hasOwnProperty('useMasterKey')) {
  652. firstOptions.useMasterKey = options.useMasterKey;
  653. }
  654. if (options && options.hasOwnProperty('sessionToken')) {
  655. firstOptions.sessionToken = options.sessionToken;
  656. }
  657. if (options && options.hasOwnProperty('context') && (0, _typeof2.default)(options.context) === 'object') {
  658. firstOptions.context = options.context;
  659. }
  660. return this.first(firstOptions).then(function (response) {
  661. if (response) {
  662. return response;
  663. }
  664. var errorObject = new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'Object not found.');
  665. return _promise.default.reject(errorObject);
  666. });
  667. }
  668. /**
  669. * Retrieves a list of ParseObjects that satisfy this query.
  670. *
  671. * @param {object} options Valid options
  672. * are:<ul>
  673. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  674. * be used for this request.
  675. * <li>sessionToken: A valid session token, used for making a request on
  676. * behalf of a specific user.
  677. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  678. * </ul>
  679. *
  680. * @returns {Promise} A promise that is resolved with the results when
  681. * the query completes.
  682. */
  683. }, {
  684. key: "find",
  685. value: function (options
  686. /*:: ?: FullOptions*/
  687. )
  688. /*: Promise<Array<ParseObject>>*/
  689. {
  690. var _this3 = this;
  691. options = options || {};
  692. var findOptions = {};
  693. if (options.hasOwnProperty('useMasterKey')) {
  694. findOptions.useMasterKey = options.useMasterKey;
  695. }
  696. if (options.hasOwnProperty('sessionToken')) {
  697. findOptions.sessionToken = options.sessionToken;
  698. }
  699. if (options.hasOwnProperty('context') && (0, _typeof2.default)(options.context) === 'object') {
  700. findOptions.context = options.context;
  701. }
  702. this._setRequestTask(findOptions);
  703. var controller = _CoreManager.default.getQueryController();
  704. var select = this._select;
  705. if (this._queriesLocalDatastore) {
  706. return this._handleOfflineQuery(this.toJSON());
  707. }
  708. return (0, _find.default)(controller).call(controller, this.className, this.toJSON(), findOptions).then(function (response) {
  709. var _context5; // Return generic object when explain is used
  710. if (_this3._explain) {
  711. return response.results;
  712. }
  713. var results = (0, _map2.default)(_context5 = response.results).call(_context5, function (data) {
  714. // In cases of relations, the server may send back a className
  715. // on the top level of the payload
  716. var override = response.className || _this3.className;
  717. if (!data.className) {
  718. data.className = override;
  719. } // Make sure the data object contains keys for all objects that
  720. // have been requested with a select, so that our cached state
  721. // updates correctly.
  722. if (select) {
  723. handleSelectResult(data, select);
  724. }
  725. return _ParseObject.default.fromJSON(data, !select);
  726. });
  727. var count = response.count;
  728. if (typeof count === 'number') {
  729. return {
  730. results: results,
  731. count: count
  732. };
  733. }
  734. return results;
  735. });
  736. }
  737. /**
  738. * Retrieves a complete list of ParseObjects that satisfy this query.
  739. * Using `eachBatch` under the hood to fetch all the valid objects.
  740. *
  741. * @param {object} options Valid options are:<ul>
  742. * <li>batchSize: How many objects to yield in each batch (default: 100)
  743. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  744. * be used for this request.
  745. * <li>sessionToken: A valid session token, used for making a request on
  746. * behalf of a specific user.
  747. * </ul>
  748. * @returns {Promise} A promise that is resolved with the results when
  749. * the query completes.
  750. */
  751. }, {
  752. key: "findAll",
  753. value: function () {
  754. var _findAll = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(options
  755. /*:: ?: BatchOptions*/
  756. ) {
  757. var result;
  758. return _regenerator.default.wrap(function (_context7) {
  759. while (1) {
  760. switch (_context7.prev = _context7.next) {
  761. case 0:
  762. result
  763. /*: ParseObject[]*/
  764. = [];
  765. _context7.next = 3;
  766. return this.eachBatch(function (objects
  767. /*: ParseObject[]*/
  768. ) {
  769. var _context6;
  770. result = (0, _concat.default)(_context6 = []).call(_context6, (0, _toConsumableArray2.default)(result), (0, _toConsumableArray2.default)(objects));
  771. }, options);
  772. case 3:
  773. return _context7.abrupt("return", result);
  774. case 4:
  775. case "end":
  776. return _context7.stop();
  777. }
  778. }
  779. }, _callee2, this);
  780. }));
  781. return function () {
  782. return _findAll.apply(this, arguments);
  783. };
  784. }()
  785. /**
  786. * Counts the number of objects that match this query.
  787. *
  788. * @param {object} options
  789. * Valid options are:<ul>
  790. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  791. * be used for this request.
  792. * <li>sessionToken: A valid session token, used for making a request on
  793. * behalf of a specific user.
  794. * </ul>
  795. *
  796. * @returns {Promise} A promise that is resolved with the count when
  797. * the query completes.
  798. */
  799. }, {
  800. key: "count",
  801. value: function (options
  802. /*:: ?: FullOptions*/
  803. )
  804. /*: Promise<number>*/
  805. {
  806. options = options || {};
  807. var findOptions = {};
  808. if (options.hasOwnProperty('useMasterKey')) {
  809. findOptions.useMasterKey = options.useMasterKey;
  810. }
  811. if (options.hasOwnProperty('sessionToken')) {
  812. findOptions.sessionToken = options.sessionToken;
  813. }
  814. this._setRequestTask(findOptions);
  815. var controller = _CoreManager.default.getQueryController();
  816. var params = this.toJSON();
  817. params.limit = 0;
  818. params.count = 1;
  819. return (0, _find.default)(controller).call(controller, this.className, params, findOptions).then(function (result) {
  820. return result.count;
  821. });
  822. }
  823. /**
  824. * Executes a distinct query and returns unique values
  825. *
  826. * @param {string} key A field to find distinct values
  827. * @param {object} options
  828. * Valid options are:<ul>
  829. * <li>sessionToken: A valid session token, used for making a request on
  830. * behalf of a specific user.
  831. * </ul>
  832. *
  833. * @returns {Promise} A promise that is resolved with the query completes.
  834. */
  835. }, {
  836. key: "distinct",
  837. value: function (key
  838. /*: string*/
  839. , options
  840. /*:: ?: FullOptions*/
  841. )
  842. /*: Promise<Array<mixed>>*/
  843. {
  844. options = options || {};
  845. var distinctOptions = {};
  846. distinctOptions.useMasterKey = true;
  847. if (options.hasOwnProperty('sessionToken')) {
  848. distinctOptions.sessionToken = options.sessionToken;
  849. }
  850. this._setRequestTask(distinctOptions);
  851. var controller = _CoreManager.default.getQueryController();
  852. var params = {
  853. distinct: key,
  854. where: this._where,
  855. hint: this._hint
  856. };
  857. return controller.aggregate(this.className, params, distinctOptions).then(function (results) {
  858. return results.results;
  859. });
  860. }
  861. /**
  862. * Executes an aggregate query and returns aggregate results
  863. *
  864. * @param {(Array|object)} pipeline Array or Object of stages to process query
  865. * @param {object} options Valid options are:<ul>
  866. * <li>sessionToken: A valid session token, used for making a request on
  867. * behalf of a specific user.
  868. * </ul>
  869. *
  870. * @returns {Promise} A promise that is resolved with the query completes.
  871. */
  872. }, {
  873. key: "aggregate",
  874. value: function (pipeline
  875. /*: mixed*/
  876. , options
  877. /*:: ?: FullOptions*/
  878. )
  879. /*: Promise<Array<mixed>>*/
  880. {
  881. options = options || {};
  882. var aggregateOptions = {};
  883. aggregateOptions.useMasterKey = true;
  884. if (options.hasOwnProperty('sessionToken')) {
  885. aggregateOptions.sessionToken = options.sessionToken;
  886. }
  887. this._setRequestTask(aggregateOptions);
  888. var controller = _CoreManager.default.getQueryController();
  889. if (!(0, _isArray.default)(pipeline) && (0, _typeof2.default)(pipeline) !== 'object') {
  890. throw new Error('Invalid pipeline must be Array or Object');
  891. }
  892. if ((0, _keys.default)(this._where || {}).length) {
  893. if (!(0, _isArray.default)(pipeline)) {
  894. pipeline = [pipeline];
  895. }
  896. pipeline.unshift({
  897. match: this._where
  898. });
  899. }
  900. var params = {
  901. pipeline: pipeline,
  902. hint: this._hint,
  903. explain: this._explain,
  904. readPreference: this._readPreference
  905. };
  906. return controller.aggregate(this.className, params, aggregateOptions).then(function (results) {
  907. return results.results;
  908. });
  909. }
  910. /**
  911. * Retrieves at most one Parse.Object that satisfies this query.
  912. *
  913. * Returns the object if there is one, otherwise undefined.
  914. *
  915. * @param {object} options Valid options are:<ul>
  916. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  917. * be used for this request.
  918. * <li>sessionToken: A valid session token, used for making a request on
  919. * behalf of a specific user.
  920. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  921. * </ul>
  922. *
  923. * @returns {Promise} A promise that is resolved with the object when
  924. * the query completes.
  925. */
  926. }, {
  927. key: "first",
  928. value: function (options
  929. /*:: ?: FullOptions*/
  930. )
  931. /*: Promise<ParseObject | void>*/
  932. {
  933. var _this4 = this;
  934. options = options || {};
  935. var findOptions = {};
  936. if (options.hasOwnProperty('useMasterKey')) {
  937. findOptions.useMasterKey = options.useMasterKey;
  938. }
  939. if (options.hasOwnProperty('sessionToken')) {
  940. findOptions.sessionToken = options.sessionToken;
  941. }
  942. if (options.hasOwnProperty('context') && (0, _typeof2.default)(options.context) === 'object') {
  943. findOptions.context = options.context;
  944. }
  945. this._setRequestTask(findOptions);
  946. var controller = _CoreManager.default.getQueryController();
  947. var params = this.toJSON();
  948. params.limit = 1;
  949. var select = this._select;
  950. if (this._queriesLocalDatastore) {
  951. return this._handleOfflineQuery(params).then(function (objects) {
  952. if (!objects[0]) {
  953. return undefined;
  954. }
  955. return objects[0];
  956. });
  957. }
  958. return (0, _find.default)(controller).call(controller, this.className, params, findOptions).then(function (response) {
  959. var objects = response.results;
  960. if (!objects[0]) {
  961. return undefined;
  962. }
  963. if (!objects[0].className) {
  964. objects[0].className = _this4.className;
  965. } // Make sure the data object contains keys for all objects that
  966. // have been requested with a select, so that our cached state
  967. // updates correctly.
  968. if (select) {
  969. handleSelectResult(objects[0], select);
  970. }
  971. return _ParseObject.default.fromJSON(objects[0], !select);
  972. });
  973. }
  974. /**
  975. * Iterates over objects matching a query, calling a callback for each batch.
  976. * If the callback returns a promise, the iteration will not continue until
  977. * that promise has been fulfilled. If the callback returns a rejected
  978. * promise, then iteration will stop with that error. The items are processed
  979. * in an unspecified order. The query may not have any sort order, and may
  980. * not use limit or skip.
  981. *
  982. * @param {Function} callback Callback that will be called with each result
  983. * of the query.
  984. * @param {object} options Valid options are:<ul>
  985. * <li>batchSize: How many objects to yield in each batch (default: 100)
  986. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  987. * be used for this request.
  988. * <li>sessionToken: A valid session token, used for making a request on
  989. * behalf of a specific user.
  990. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  991. * </ul>
  992. * @returns {Promise} A promise that will be fulfilled once the
  993. * iteration has completed.
  994. */
  995. }, {
  996. key: "eachBatch",
  997. value: function (callback
  998. /*: (objs: Array<ParseObject>) => Promise<*>*/
  999. , options
  1000. /*:: ?: BatchOptions*/
  1001. )
  1002. /*: Promise<void>*/
  1003. {
  1004. var _context8;
  1005. options = options || {};
  1006. if (this._order || this._skip || this._limit >= 0) {
  1007. return _promise.default.reject('Cannot iterate on a query with sort, skip, or limit.');
  1008. }
  1009. var query = new ParseQuery(this.className);
  1010. query._limit = options.batchSize || 100;
  1011. query._include = (0, _map2.default)(_context8 = this._include).call(_context8, function (i) {
  1012. return i;
  1013. });
  1014. if (this._select) {
  1015. var _context9;
  1016. query._select = (0, _map2.default)(_context9 = this._select).call(_context9, function (s) {
  1017. return s;
  1018. });
  1019. }
  1020. query._hint = this._hint;
  1021. query._where = {};
  1022. for (var _attr in this._where) {
  1023. var val = this._where[_attr];
  1024. if ((0, _isArray.default)(val)) {
  1025. query._where[_attr] = (0, _map2.default)(val).call(val, function (v) {
  1026. return v;
  1027. });
  1028. } else if (val && (0, _typeof2.default)(val) === 'object') {
  1029. var conditionMap = {};
  1030. query._where[_attr] = conditionMap;
  1031. for (var cond in val) {
  1032. conditionMap[cond] = val[cond];
  1033. }
  1034. } else {
  1035. query._where[_attr] = val;
  1036. }
  1037. }
  1038. query.ascending('objectId');
  1039. var findOptions = {};
  1040. if (options.hasOwnProperty('useMasterKey')) {
  1041. findOptions.useMasterKey = options.useMasterKey;
  1042. }
  1043. if (options.hasOwnProperty('sessionToken')) {
  1044. findOptions.sessionToken = options.sessionToken;
  1045. }
  1046. if (options.hasOwnProperty('context') && (0, _typeof2.default)(options.context) === 'object') {
  1047. findOptions.context = options.context;
  1048. }
  1049. var finished = false;
  1050. var previousResults = [];
  1051. return (0, _promiseUtils.continueWhile)(function () {
  1052. return !finished;
  1053. }, /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3() {
  1054. var _yield$Promise$all, _yield$Promise$all2, results;
  1055. return _regenerator.default.wrap(function (_context10) {
  1056. while (1) {
  1057. switch (_context10.prev = _context10.next) {
  1058. case 0:
  1059. _context10.next = 2;
  1060. return _promise.default.all([(0, _find.default)(query).call(query, findOptions), _promise.default.resolve(previousResults.length > 0 && callback(previousResults))]);
  1061. case 2:
  1062. _yield$Promise$all = _context10.sent;
  1063. _yield$Promise$all2 = (0, _slicedToArray2.default)(_yield$Promise$all, 1);
  1064. results = _yield$Promise$all2[0];
  1065. if (!(results.length >= query._limit)) {
  1066. _context10.next = 10;
  1067. break;
  1068. }
  1069. query.greaterThan('objectId', results[results.length - 1].id);
  1070. previousResults = results;
  1071. _context10.next = 17;
  1072. break;
  1073. case 10:
  1074. if (!(results.length > 0)) {
  1075. _context10.next = 16;
  1076. break;
  1077. }
  1078. _context10.next = 13;
  1079. return _promise.default.resolve(callback(results));
  1080. case 13:
  1081. finished = true;
  1082. _context10.next = 17;
  1083. break;
  1084. case 16:
  1085. finished = true;
  1086. case 17:
  1087. case "end":
  1088. return _context10.stop();
  1089. }
  1090. }
  1091. }, _callee3);
  1092. })));
  1093. }
  1094. /**
  1095. * Iterates over each result of a query, calling a callback for each one. If
  1096. * the callback returns a promise, the iteration will not continue until
  1097. * that promise has been fulfilled. If the callback returns a rejected
  1098. * promise, then iteration will stop with that error. The items are
  1099. * processed in an unspecified order. The query may not have any sort order,
  1100. * and may not use limit or skip.
  1101. *
  1102. * @param {Function} callback Callback that will be called with each result
  1103. * of the query.
  1104. * @param {object} options Valid options are:<ul>
  1105. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1106. * be used for this request.
  1107. * <li>sessionToken: A valid session token, used for making a request on
  1108. * behalf of a specific user.
  1109. * </ul>
  1110. * @returns {Promise} A promise that will be fulfilled once the
  1111. * iteration has completed.
  1112. */
  1113. }, {
  1114. key: "each",
  1115. value: function (callback
  1116. /*: (obj: ParseObject) => any*/
  1117. , options
  1118. /*:: ?: BatchOptions*/
  1119. )
  1120. /*: Promise<void>*/
  1121. {
  1122. return this.eachBatch(function (results) {
  1123. var callbacksDone = _promise.default.resolve();
  1124. (0, _forEach.default)(results).call(results, function (result) {
  1125. callbacksDone = callbacksDone.then(function () {
  1126. return callback(result);
  1127. });
  1128. });
  1129. return callbacksDone;
  1130. }, options);
  1131. }
  1132. /**
  1133. * Adds a hint to force index selection. (https://docs.mongodb.com/manual/reference/operator/meta/hint/)
  1134. *
  1135. * @param {(string|object)} value String or Object of index that should be used when executing query
  1136. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1137. */
  1138. }, {
  1139. key: "hint",
  1140. value: function (value
  1141. /*: mixed*/
  1142. )
  1143. /*: ParseQuery*/
  1144. {
  1145. if (typeof value === 'undefined') {
  1146. delete this._hint;
  1147. }
  1148. this._hint = value;
  1149. return this;
  1150. }
  1151. /**
  1152. * Investigates the query execution plan. Useful for optimizing queries. (https://docs.mongodb.com/manual/reference/operator/meta/explain/)
  1153. *
  1154. * @param {boolean} explain Used to toggle the information on the query plan.
  1155. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1156. */
  1157. }, {
  1158. key: "explain",
  1159. value: function ()
  1160. /*: ParseQuery*/
  1161. {
  1162. var _explain
  1163. /*: boolean*/
  1164. = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  1165. if (typeof _explain !== 'boolean') {
  1166. throw new Error('You can only set explain to a boolean value');
  1167. }
  1168. this._explain = _explain;
  1169. return this;
  1170. }
  1171. /**
  1172. * Iterates over each result of a query, calling a callback for each one. If
  1173. * the callback returns a promise, the iteration will not continue until
  1174. * that promise has been fulfilled. If the callback returns a rejected
  1175. * promise, then iteration will stop with that error. The items are
  1176. * processed in an unspecified order. The query may not have any sort order,
  1177. * and may not use limit or skip.
  1178. *
  1179. * @param {Function} callback Callback <ul>
  1180. * <li>currentObject: The current Parse.Object being processed in the array.</li>
  1181. * <li>index: The index of the current Parse.Object being processed in the array.</li>
  1182. * <li>query: The query map was called upon.</li>
  1183. * </ul>
  1184. *
  1185. * @param {object} options Valid options are:<ul>
  1186. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1187. * be used for this request.
  1188. * <li>sessionToken: A valid session token, used for making a request on
  1189. * behalf of a specific user.
  1190. * </ul>
  1191. * @returns {Promise} A promise that will be fulfilled once the
  1192. * iteration has completed.
  1193. */
  1194. }, {
  1195. key: "map",
  1196. value: function () {
  1197. var _map = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee4(callback
  1198. /*: (currentObject: ParseObject, index: number, query: ParseQuery) => any*/
  1199. , options
  1200. /*:: ?: BatchOptions*/
  1201. ) {
  1202. var _this5 = this;
  1203. var array, index;
  1204. return _regenerator.default.wrap(function (_context11) {
  1205. while (1) {
  1206. switch (_context11.prev = _context11.next) {
  1207. case 0:
  1208. array = [];
  1209. index = 0;
  1210. _context11.next = 4;
  1211. return this.each(function (object) {
  1212. return _promise.default.resolve(callback(object, index, _this5)).then(function (result) {
  1213. array.push(result);
  1214. index += 1;
  1215. });
  1216. }, options);
  1217. case 4:
  1218. return _context11.abrupt("return", array);
  1219. case 5:
  1220. case "end":
  1221. return _context11.stop();
  1222. }
  1223. }
  1224. }, _callee4, this);
  1225. }));
  1226. return function () {
  1227. return _map.apply(this, arguments);
  1228. };
  1229. }()
  1230. /**
  1231. * Iterates over each result of a query, calling a callback for each one. If
  1232. * the callback returns a promise, the iteration will not continue until
  1233. * that promise has been fulfilled. If the callback returns a rejected
  1234. * promise, then iteration will stop with that error. The items are
  1235. * processed in an unspecified order. The query may not have any sort order,
  1236. * and may not use limit or skip.
  1237. *
  1238. * @param {Function} callback Callback <ul>
  1239. * <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>
  1240. * <li>currentObject: The current Parse.Object being processed in the array.</li>
  1241. * <li>index: The index of the current Parse.Object being processed in the array.</li>
  1242. * </ul>
  1243. * @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.
  1244. * @param {object} options Valid options are:<ul>
  1245. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1246. * be used for this request.
  1247. * <li>sessionToken: A valid session token, used for making a request on
  1248. * behalf of a specific user.
  1249. * </ul>
  1250. * @returns {Promise} A promise that will be fulfilled once the
  1251. * iteration has completed.
  1252. */
  1253. }, {
  1254. key: "reduce",
  1255. value: function () {
  1256. var _reduce = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee5(callback
  1257. /*: (accumulator: any, currentObject: ParseObject, index: number) => any*/
  1258. , initialValue
  1259. /*: any*/
  1260. , options
  1261. /*:: ?: BatchOptions*/
  1262. ) {
  1263. var accumulator, index;
  1264. return _regenerator.default.wrap(function (_context12) {
  1265. while (1) {
  1266. switch (_context12.prev = _context12.next) {
  1267. case 0:
  1268. accumulator = initialValue;
  1269. index = 0;
  1270. _context12.next = 4;
  1271. return this.each(function (object) {
  1272. // If no initial value was given, we take the first object from the query
  1273. // as the initial value and don't call the callback with it.
  1274. if (index === 0 && initialValue === undefined) {
  1275. accumulator = object;
  1276. index += 1;
  1277. return;
  1278. }
  1279. return _promise.default.resolve(callback(accumulator, object, index)).then(function (result) {
  1280. accumulator = result;
  1281. index += 1;
  1282. });
  1283. }, options);
  1284. case 4:
  1285. if (!(index === 0 && initialValue === undefined)) {
  1286. _context12.next = 6;
  1287. break;
  1288. }
  1289. throw new TypeError('Reducing empty query result set with no initial value');
  1290. case 6:
  1291. return _context12.abrupt("return", accumulator);
  1292. case 7:
  1293. case "end":
  1294. return _context12.stop();
  1295. }
  1296. }
  1297. }, _callee5, this);
  1298. }));
  1299. return function () {
  1300. return _reduce.apply(this, arguments);
  1301. };
  1302. }()
  1303. /**
  1304. * Iterates over each result of a query, calling a callback for each one. If
  1305. * the callback returns a promise, the iteration will not continue until
  1306. * that promise has been fulfilled. If the callback returns a rejected
  1307. * promise, then iteration will stop with that error. The items are
  1308. * processed in an unspecified order. The query may not have any sort order,
  1309. * and may not use limit or skip.
  1310. *
  1311. * @param {Function} callback Callback <ul>
  1312. * <li>currentObject: The current Parse.Object being processed in the array.</li>
  1313. * <li>index: The index of the current Parse.Object being processed in the array.</li>
  1314. * <li>query: The query filter was called upon.</li>
  1315. * </ul>
  1316. *
  1317. * @param {object} options Valid options are:<ul>
  1318. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1319. * be used for this request.
  1320. * <li>sessionToken: A valid session token, used for making a request on
  1321. * behalf of a specific user.
  1322. * </ul>
  1323. * @returns {Promise} A promise that will be fulfilled once the
  1324. * iteration has completed.
  1325. */
  1326. }, {
  1327. key: "filter",
  1328. value: function () {
  1329. var _filter = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee6(callback
  1330. /*: (currentObject: ParseObject, index: number, query: ParseQuery) => boolean*/
  1331. , options
  1332. /*:: ?: BatchOptions*/
  1333. ) {
  1334. var _this6 = this;
  1335. var array, index;
  1336. return _regenerator.default.wrap(function (_context13) {
  1337. while (1) {
  1338. switch (_context13.prev = _context13.next) {
  1339. case 0:
  1340. array = [];
  1341. index = 0;
  1342. _context13.next = 4;
  1343. return this.each(function (object) {
  1344. return _promise.default.resolve(callback(object, index, _this6)).then(function (flag) {
  1345. if (flag) {
  1346. array.push(object);
  1347. }
  1348. index += 1;
  1349. });
  1350. }, options);
  1351. case 4:
  1352. return _context13.abrupt("return", array);
  1353. case 5:
  1354. case "end":
  1355. return _context13.stop();
  1356. }
  1357. }
  1358. }, _callee6, this);
  1359. }));
  1360. return function () {
  1361. return _filter.apply(this, arguments);
  1362. };
  1363. }()
  1364. /** Query Conditions * */
  1365. /**
  1366. * Adds a constraint to the query that requires a particular key's value to
  1367. * be equal to the provided value.
  1368. *
  1369. * @param {string} key The key to check.
  1370. * @param value The value that the Parse.Object must contain.
  1371. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1372. */
  1373. }, {
  1374. key: "equalTo",
  1375. value: function (key
  1376. /*: string | { [key: string]: any }*/
  1377. , value
  1378. /*: ?mixed*/
  1379. )
  1380. /*: ParseQuery*/
  1381. {
  1382. var _this7 = this;
  1383. if (key && (0, _typeof2.default)(key) === 'object') {
  1384. var _context14;
  1385. (0, _forEach.default)(_context14 = (0, _entries.default)(key)).call(_context14, function (_ref2) {
  1386. var _ref3 = (0, _slicedToArray2.default)(_ref2, 2),
  1387. k = _ref3[0],
  1388. val = _ref3[1];
  1389. return _this7.equalTo(k, val);
  1390. });
  1391. return this;
  1392. }
  1393. if (typeof value === 'undefined') {
  1394. return this.doesNotExist(key);
  1395. }
  1396. this._where[key] = (0, _encode.default)(value, false, true);
  1397. return this;
  1398. }
  1399. /**
  1400. * Adds a constraint to the query that requires a particular key's value to
  1401. * be not equal to the provided value.
  1402. *
  1403. * @param {string} key The key to check.
  1404. * @param value The value that must not be equalled.
  1405. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1406. */
  1407. }, {
  1408. key: "notEqualTo",
  1409. value: function (key
  1410. /*: string | { [key: string]: any }*/
  1411. , value
  1412. /*: ?mixed*/
  1413. )
  1414. /*: ParseQuery*/
  1415. {
  1416. var _this8 = this;
  1417. if (key && (0, _typeof2.default)(key) === 'object') {
  1418. var _context15;
  1419. (0, _forEach.default)(_context15 = (0, _entries.default)(key)).call(_context15, function (_ref4) {
  1420. var _ref5 = (0, _slicedToArray2.default)(_ref4, 2),
  1421. k = _ref5[0],
  1422. val = _ref5[1];
  1423. return _this8.notEqualTo(k, val);
  1424. });
  1425. return this;
  1426. }
  1427. return this._addCondition(key, '$ne', value);
  1428. }
  1429. /**
  1430. * Adds a constraint to the query that requires a particular key's value to
  1431. * be less than the provided value.
  1432. *
  1433. * @param {string} key The key to check.
  1434. * @param value The value that provides an upper bound.
  1435. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1436. */
  1437. }, {
  1438. key: "lessThan",
  1439. value: function (key
  1440. /*: string*/
  1441. , value
  1442. /*: mixed*/
  1443. )
  1444. /*: ParseQuery*/
  1445. {
  1446. return this._addCondition(key, '$lt', value);
  1447. }
  1448. /**
  1449. * Adds a constraint to the query that requires a particular key's value to
  1450. * be greater than the provided value.
  1451. *
  1452. * @param {string} key The key to check.
  1453. * @param value The value that provides an lower bound.
  1454. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1455. */
  1456. }, {
  1457. key: "greaterThan",
  1458. value: function (key
  1459. /*: string*/
  1460. , value
  1461. /*: mixed*/
  1462. )
  1463. /*: ParseQuery*/
  1464. {
  1465. return this._addCondition(key, '$gt', value);
  1466. }
  1467. /**
  1468. * Adds a constraint to the query that requires a particular key's value to
  1469. * be less than or equal to the provided value.
  1470. *
  1471. * @param {string} key The key to check.
  1472. * @param value The value that provides an upper bound.
  1473. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1474. */
  1475. }, {
  1476. key: "lessThanOrEqualTo",
  1477. value: function (key
  1478. /*: string*/
  1479. , value
  1480. /*: mixed*/
  1481. )
  1482. /*: ParseQuery*/
  1483. {
  1484. return this._addCondition(key, '$lte', value);
  1485. }
  1486. /**
  1487. * Adds a constraint to the query that requires a particular key's value to
  1488. * be greater than or equal to the provided value.
  1489. *
  1490. * @param {string} key The key to check.
  1491. * @param {*} value The value that provides an lower bound.
  1492. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1493. */
  1494. }, {
  1495. key: "greaterThanOrEqualTo",
  1496. value: function (key
  1497. /*: string*/
  1498. , value
  1499. /*: mixed*/
  1500. )
  1501. /*: ParseQuery*/
  1502. {
  1503. return this._addCondition(key, '$gte', value);
  1504. }
  1505. /**
  1506. * Adds a constraint to the query that requires a particular key's value to
  1507. * be contained in the provided list of values.
  1508. *
  1509. * @param {string} key The key to check.
  1510. * @param {*} value The values that will match.
  1511. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1512. */
  1513. }, {
  1514. key: "containedIn",
  1515. value: function (key
  1516. /*: string*/
  1517. , value
  1518. /*: mixed*/
  1519. )
  1520. /*: ParseQuery*/
  1521. {
  1522. return this._addCondition(key, '$in', value);
  1523. }
  1524. /**
  1525. * Adds a constraint to the query that requires a particular key's value to
  1526. * not be contained in the provided list of values.
  1527. *
  1528. * @param {string} key The key to check.
  1529. * @param {*} value The values that will not match.
  1530. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1531. */
  1532. }, {
  1533. key: "notContainedIn",
  1534. value: function (key
  1535. /*: string*/
  1536. , value
  1537. /*: mixed*/
  1538. )
  1539. /*: ParseQuery*/
  1540. {
  1541. return this._addCondition(key, '$nin', value);
  1542. }
  1543. /**
  1544. * Adds a constraint to the query that requires a particular key's value to
  1545. * be contained by the provided list of values. Get objects where all array elements match.
  1546. *
  1547. * @param {string} key The key to check.
  1548. * @param {Array} values The values that will match.
  1549. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1550. */
  1551. }, {
  1552. key: "containedBy",
  1553. value: function (key
  1554. /*: string*/
  1555. , values
  1556. /*: Array<mixed>*/
  1557. )
  1558. /*: ParseQuery*/
  1559. {
  1560. return this._addCondition(key, '$containedBy', values);
  1561. }
  1562. /**
  1563. * Adds a constraint to the query that requires a particular key's value to
  1564. * contain each one of the provided list of values.
  1565. *
  1566. * @param {string} key The key to check. This key's value must be an array.
  1567. * @param {Array} values The values that will match.
  1568. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1569. */
  1570. }, {
  1571. key: "containsAll",
  1572. value: function (key
  1573. /*: string*/
  1574. , values
  1575. /*: Array<mixed>*/
  1576. )
  1577. /*: ParseQuery*/
  1578. {
  1579. return this._addCondition(key, '$all', values);
  1580. }
  1581. /**
  1582. * Adds a constraint to the query that requires a particular key's value to
  1583. * contain each one of the provided list of values starting with given strings.
  1584. *
  1585. * @param {string} key The key to check. This key's value must be an array.
  1586. * @param {Array<string>} values The string values that will match as starting string.
  1587. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1588. */
  1589. }, {
  1590. key: "containsAllStartingWith",
  1591. value: function (key
  1592. /*: string*/
  1593. , values
  1594. /*: Array<string>*/
  1595. )
  1596. /*: ParseQuery*/
  1597. {
  1598. var _this = this;
  1599. if (!(0, _isArray.default)(values)) {
  1600. values = [values];
  1601. }
  1602. var regexObject = (0, _map2.default)(values).call(values, function (value) {
  1603. return {
  1604. $regex: _this._regexStartWith(value)
  1605. };
  1606. });
  1607. return this.containsAll(key, regexObject);
  1608. }
  1609. /**
  1610. * Adds a constraint for finding objects that contain the given key.
  1611. *
  1612. * @param {string} key The key that should exist.
  1613. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1614. */
  1615. }, {
  1616. key: "exists",
  1617. value: function (key
  1618. /*: string*/
  1619. )
  1620. /*: ParseQuery*/
  1621. {
  1622. return this._addCondition(key, '$exists', true);
  1623. }
  1624. /**
  1625. * Adds a constraint for finding objects that do not contain a given key.
  1626. *
  1627. * @param {string} key The key that should not exist
  1628. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1629. */
  1630. }, {
  1631. key: "doesNotExist",
  1632. value: function (key
  1633. /*: string*/
  1634. )
  1635. /*: ParseQuery*/
  1636. {
  1637. return this._addCondition(key, '$exists', false);
  1638. }
  1639. /**
  1640. * Adds a regular expression constraint for finding string values that match
  1641. * the provided regular expression.
  1642. * This may be slow for large datasets.
  1643. *
  1644. * @param {string} key The key that the string to match is stored in.
  1645. * @param {RegExp} regex The regular expression pattern to match.
  1646. * @param {string} modifiers The regular expression mode.
  1647. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1648. */
  1649. }, {
  1650. key: "matches",
  1651. value: function (key
  1652. /*: string*/
  1653. , regex
  1654. /*: RegExp*/
  1655. , modifiers
  1656. /*: string*/
  1657. )
  1658. /*: ParseQuery*/
  1659. {
  1660. this._addCondition(key, '$regex', regex);
  1661. if (!modifiers) {
  1662. modifiers = '';
  1663. }
  1664. if (regex.ignoreCase) {
  1665. modifiers += 'i';
  1666. }
  1667. if (regex.multiline) {
  1668. modifiers += 'm';
  1669. }
  1670. if (modifiers.length) {
  1671. this._addCondition(key, '$options', modifiers);
  1672. }
  1673. return this;
  1674. }
  1675. /**
  1676. * Adds a constraint that requires that a key's value matches a Parse.Query
  1677. * constraint.
  1678. *
  1679. * @param {string} key The key that the contains the object to match the
  1680. * query.
  1681. * @param {Parse.Query} query The query that should match.
  1682. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1683. */
  1684. }, {
  1685. key: "matchesQuery",
  1686. value: function (key
  1687. /*: string*/
  1688. , query
  1689. /*: ParseQuery*/
  1690. )
  1691. /*: ParseQuery*/
  1692. {
  1693. var queryJSON = query.toJSON();
  1694. queryJSON.className = query.className;
  1695. return this._addCondition(key, '$inQuery', queryJSON);
  1696. }
  1697. /**
  1698. * Adds a constraint that requires that a key's value not matches a
  1699. * Parse.Query constraint.
  1700. *
  1701. * @param {string} key The key that the contains the object to match the
  1702. * query.
  1703. * @param {Parse.Query} query The query that should not match.
  1704. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1705. */
  1706. }, {
  1707. key: "doesNotMatchQuery",
  1708. value: function (key
  1709. /*: string*/
  1710. , query
  1711. /*: ParseQuery*/
  1712. )
  1713. /*: ParseQuery*/
  1714. {
  1715. var queryJSON = query.toJSON();
  1716. queryJSON.className = query.className;
  1717. return this._addCondition(key, '$notInQuery', queryJSON);
  1718. }
  1719. /**
  1720. * Adds a constraint that requires that a key's value matches a value in
  1721. * an object returned by a different Parse.Query.
  1722. *
  1723. * @param {string} key The key that contains the value that is being
  1724. * matched.
  1725. * @param {string} queryKey The key in the objects returned by the query to
  1726. * match against.
  1727. * @param {Parse.Query} query The query to run.
  1728. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1729. */
  1730. }, {
  1731. key: "matchesKeyInQuery",
  1732. value: function (key
  1733. /*: string*/
  1734. , queryKey
  1735. /*: string*/
  1736. , query
  1737. /*: ParseQuery*/
  1738. )
  1739. /*: ParseQuery*/
  1740. {
  1741. var queryJSON = query.toJSON();
  1742. queryJSON.className = query.className;
  1743. return this._addCondition(key, '$select', {
  1744. key: queryKey,
  1745. query: queryJSON
  1746. });
  1747. }
  1748. /**
  1749. * Adds a constraint that requires that a key's value not match a value in
  1750. * an object returned by a different Parse.Query.
  1751. *
  1752. * @param {string} key The key that contains the value that is being
  1753. * excluded.
  1754. * @param {string} queryKey The key in the objects returned by the query to
  1755. * match against.
  1756. * @param {Parse.Query} query The query to run.
  1757. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1758. */
  1759. }, {
  1760. key: "doesNotMatchKeyInQuery",
  1761. value: function (key
  1762. /*: string*/
  1763. , queryKey
  1764. /*: string*/
  1765. , query
  1766. /*: ParseQuery*/
  1767. )
  1768. /*: ParseQuery*/
  1769. {
  1770. var queryJSON = query.toJSON();
  1771. queryJSON.className = query.className;
  1772. return this._addCondition(key, '$dontSelect', {
  1773. key: queryKey,
  1774. query: queryJSON
  1775. });
  1776. }
  1777. /**
  1778. * Adds a constraint for finding string values that contain a provided
  1779. * string. This may be slow for large datasets.
  1780. *
  1781. * @param {string} key The key that the string to match is stored in.
  1782. * @param {string} substring The substring that the value must contain.
  1783. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1784. */
  1785. }, {
  1786. key: "contains",
  1787. value: function (key
  1788. /*: string*/
  1789. , substring
  1790. /*: string*/
  1791. )
  1792. /*: ParseQuery*/
  1793. {
  1794. if (typeof substring !== 'string') {
  1795. throw new Error('The value being searched for must be a string.');
  1796. }
  1797. return this._addCondition(key, '$regex', quote(substring));
  1798. }
  1799. /**
  1800. * Adds a constraint for finding string values that contain a provided
  1801. * string. This may be slow for large datasets. Requires Parse-Server > 2.5.0
  1802. *
  1803. * In order to sort you must use select and ascending ($score is required)
  1804. * <pre>
  1805. * query.fullText('field', 'term');
  1806. * query.ascending('$score');
  1807. * query.select('$score');
  1808. * </pre>
  1809. *
  1810. * To retrieve the weight / rank
  1811. * <pre>
  1812. * object->get('score');
  1813. * </pre>
  1814. *
  1815. * You can define optionals by providing an object as a third parameter
  1816. * <pre>
  1817. * query.fullText('field', 'term', { language: 'es', diacriticSensitive: true });
  1818. * </pre>
  1819. *
  1820. * @param {string} key The key that the string to match is stored in.
  1821. * @param {string} value The string to search
  1822. * @param {object} options (Optional)
  1823. * @param {string} options.language The language that determines the list of stop words for the search and the rules for the stemmer and tokenizer.
  1824. * @param {boolean} options.caseSensitive A boolean flag to enable or disable case sensitive search.
  1825. * @param {boolean} options.diacriticSensitive A boolean flag to enable or disable diacritic sensitive search.
  1826. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1827. */
  1828. }, {
  1829. key: "fullText",
  1830. value: function (key
  1831. /*: string*/
  1832. , value
  1833. /*: string*/
  1834. , options
  1835. /*: ?Object*/
  1836. )
  1837. /*: ParseQuery*/
  1838. {
  1839. options = options || {};
  1840. if (!key) {
  1841. throw new Error('A key is required.');
  1842. }
  1843. if (!value) {
  1844. throw new Error('A search term is required');
  1845. }
  1846. if (typeof value !== 'string') {
  1847. throw new Error('The value being searched for must be a string.');
  1848. }
  1849. var fullOptions = {};
  1850. fullOptions.$term = value;
  1851. for (var option in options) {
  1852. switch (option) {
  1853. case 'language':
  1854. fullOptions.$language = options[option];
  1855. break;
  1856. case 'caseSensitive':
  1857. fullOptions.$caseSensitive = options[option];
  1858. break;
  1859. case 'diacriticSensitive':
  1860. fullOptions.$diacriticSensitive = options[option];
  1861. break;
  1862. default:
  1863. throw new Error("Unknown option: ".concat(option));
  1864. }
  1865. }
  1866. return this._addCondition(key, '$text', {
  1867. $search: fullOptions
  1868. });
  1869. }
  1870. /**
  1871. * Method to sort the full text search by text score
  1872. *
  1873. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1874. */
  1875. }, {
  1876. key: "sortByTextScore",
  1877. value: function () {
  1878. this.ascending('$score');
  1879. this.select(['$score']);
  1880. return this;
  1881. }
  1882. /**
  1883. * Adds a constraint for finding string values that start with a provided
  1884. * string. This query will use the backend index, so it will be fast even
  1885. * for large datasets.
  1886. *
  1887. * @param {string} key The key that the string to match is stored in.
  1888. * @param {string} prefix The substring that the value must start with.
  1889. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1890. */
  1891. }, {
  1892. key: "startsWith",
  1893. value: function (key
  1894. /*: string*/
  1895. , prefix
  1896. /*: string*/
  1897. )
  1898. /*: ParseQuery*/
  1899. {
  1900. if (typeof prefix !== 'string') {
  1901. throw new Error('The value being searched for must be a string.');
  1902. }
  1903. return this._addCondition(key, '$regex', this._regexStartWith(prefix));
  1904. }
  1905. /**
  1906. * Adds a constraint for finding string values that end with a provided
  1907. * string. This will be slow for large datasets.
  1908. *
  1909. * @param {string} key The key that the string to match is stored in.
  1910. * @param {string} suffix The substring that the value must end with.
  1911. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1912. */
  1913. }, {
  1914. key: "endsWith",
  1915. value: function (key
  1916. /*: string*/
  1917. , suffix
  1918. /*: string*/
  1919. )
  1920. /*: ParseQuery*/
  1921. {
  1922. if (typeof suffix !== 'string') {
  1923. throw new Error('The value being searched for must be a string.');
  1924. }
  1925. return this._addCondition(key, '$regex', "".concat(quote(suffix), "$"));
  1926. }
  1927. /**
  1928. * Adds a proximity based constraint for finding objects with key point
  1929. * values near the point given.
  1930. *
  1931. * @param {string} key The key that the Parse.GeoPoint is stored in.
  1932. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  1933. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1934. */
  1935. }, {
  1936. key: "near",
  1937. value: function (key
  1938. /*: string*/
  1939. , point
  1940. /*: ParseGeoPoint*/
  1941. )
  1942. /*: ParseQuery*/
  1943. {
  1944. if (!(point instanceof _ParseGeoPoint.default)) {
  1945. // Try to cast it as a GeoPoint
  1946. point = new _ParseGeoPoint.default(point);
  1947. }
  1948. return this._addCondition(key, '$nearSphere', point);
  1949. }
  1950. /**
  1951. * Adds a proximity based constraint for finding objects with key point
  1952. * values near the point given and within the maximum distance given.
  1953. *
  1954. * @param {string} key The key that the Parse.GeoPoint is stored in.
  1955. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  1956. * @param {number} maxDistance Maximum distance (in radians) of results to return.
  1957. * @param {boolean} sorted A Bool value that is true if results should be
  1958. * sorted by distance ascending, false is no sorting is required,
  1959. * defaults to true.
  1960. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1961. */
  1962. }, {
  1963. key: "withinRadians",
  1964. value: function (key
  1965. /*: string*/
  1966. , point
  1967. /*: ParseGeoPoint*/
  1968. , maxDistance
  1969. /*: number*/
  1970. , sorted
  1971. /*: boolean*/
  1972. )
  1973. /*: ParseQuery*/
  1974. {
  1975. if (sorted || sorted === undefined) {
  1976. this.near(key, point);
  1977. return this._addCondition(key, '$maxDistance', maxDistance);
  1978. }
  1979. return this._addCondition(key, '$geoWithin', {
  1980. $centerSphere: [[point.longitude, point.latitude], maxDistance]
  1981. });
  1982. }
  1983. /**
  1984. * Adds a proximity based constraint for finding objects with key point
  1985. * values near the point given and within the maximum distance given.
  1986. * Radius of earth used is 3958.8 miles.
  1987. *
  1988. * @param {string} key The key that the Parse.GeoPoint is stored in.
  1989. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  1990. * @param {number} maxDistance Maximum distance (in miles) of results to return.
  1991. * @param {boolean} sorted A Bool value that is true if results should be
  1992. * sorted by distance ascending, false is no sorting is required,
  1993. * defaults to true.
  1994. * @returns {Parse.Query} Returns the query, so you can chain this call.
  1995. */
  1996. }, {
  1997. key: "withinMiles",
  1998. value: function (key
  1999. /*: string*/
  2000. , point
  2001. /*: ParseGeoPoint*/
  2002. , maxDistance
  2003. /*: number*/
  2004. , sorted
  2005. /*: boolean*/
  2006. )
  2007. /*: ParseQuery*/
  2008. {
  2009. return this.withinRadians(key, point, maxDistance / 3958.8, sorted);
  2010. }
  2011. /**
  2012. * Adds a proximity based constraint for finding objects with key point
  2013. * values near the point given and within the maximum distance given.
  2014. * Radius of earth used is 6371.0 kilometers.
  2015. *
  2016. * @param {string} key The key that the Parse.GeoPoint is stored in.
  2017. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  2018. * @param {number} maxDistance Maximum distance (in kilometers) of results to return.
  2019. * @param {boolean} sorted A Bool value that is true if results should be
  2020. * sorted by distance ascending, false is no sorting is required,
  2021. * defaults to true.
  2022. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2023. */
  2024. }, {
  2025. key: "withinKilometers",
  2026. value: function (key
  2027. /*: string*/
  2028. , point
  2029. /*: ParseGeoPoint*/
  2030. , maxDistance
  2031. /*: number*/
  2032. , sorted
  2033. /*: boolean*/
  2034. )
  2035. /*: ParseQuery*/
  2036. {
  2037. return this.withinRadians(key, point, maxDistance / 6371.0, sorted);
  2038. }
  2039. /**
  2040. * Adds a constraint to the query that requires a particular key's
  2041. * coordinates be contained within a given rectangular geographic bounding
  2042. * box.
  2043. *
  2044. * @param {string} key The key to be constrained.
  2045. * @param {Parse.GeoPoint} southwest
  2046. * The lower-left inclusive corner of the box.
  2047. * @param {Parse.GeoPoint} northeast
  2048. * The upper-right inclusive corner of the box.
  2049. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2050. */
  2051. }, {
  2052. key: "withinGeoBox",
  2053. value: function (key
  2054. /*: string*/
  2055. , southwest
  2056. /*: ParseGeoPoint*/
  2057. , northeast
  2058. /*: ParseGeoPoint*/
  2059. )
  2060. /*: ParseQuery*/
  2061. {
  2062. if (!(southwest instanceof _ParseGeoPoint.default)) {
  2063. southwest = new _ParseGeoPoint.default(southwest);
  2064. }
  2065. if (!(northeast instanceof _ParseGeoPoint.default)) {
  2066. northeast = new _ParseGeoPoint.default(northeast);
  2067. }
  2068. this._addCondition(key, '$within', {
  2069. $box: [southwest, northeast]
  2070. });
  2071. return this;
  2072. }
  2073. /**
  2074. * Adds a constraint to the query that requires a particular key's
  2075. * coordinates be contained within and on the bounds of a given polygon.
  2076. * Supports closed and open (last point is connected to first) paths
  2077. *
  2078. * Polygon must have at least 3 points
  2079. *
  2080. * @param {string} key The key to be constrained.
  2081. * @param {Array} points Array of Coordinates / GeoPoints
  2082. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2083. */
  2084. }, {
  2085. key: "withinPolygon",
  2086. value: function (key
  2087. /*: string*/
  2088. , points
  2089. /*: Array<Array<number>>*/
  2090. )
  2091. /*: ParseQuery*/
  2092. {
  2093. return this._addCondition(key, '$geoWithin', {
  2094. $polygon: points
  2095. });
  2096. }
  2097. /**
  2098. * Add a constraint to the query that requires a particular key's
  2099. * coordinates that contains a ParseGeoPoint
  2100. *
  2101. * @param {string} key The key to be constrained.
  2102. * @param {Parse.GeoPoint} point
  2103. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2104. */
  2105. }, {
  2106. key: "polygonContains",
  2107. value: function (key
  2108. /*: string*/
  2109. , point
  2110. /*: ParseGeoPoint*/
  2111. )
  2112. /*: ParseQuery*/
  2113. {
  2114. return this._addCondition(key, '$geoIntersects', {
  2115. $point: point
  2116. });
  2117. }
  2118. /** Query Orderings * */
  2119. /**
  2120. * Sorts the results in ascending order by the given key.
  2121. *
  2122. * @param {(string|string[])} keys The key to order by, which is a
  2123. * string of comma separated values, or an Array of keys, or multiple keys.
  2124. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2125. */
  2126. }, {
  2127. key: "ascending",
  2128. value: function ()
  2129. /*: ParseQuery*/
  2130. {
  2131. this._order = [];
  2132. for (var _len = arguments.length, keys = new Array(_len), _key5 = 0; _key5 < _len; _key5++) {
  2133. keys[_key5] = arguments[_key5];
  2134. }
  2135. return this.addAscending.apply(this, keys);
  2136. }
  2137. /**
  2138. * Sorts the results in ascending order by the given key,
  2139. * but can also add secondary sort descriptors without overwriting _order.
  2140. *
  2141. * @param {(string|string[])} keys The key to order by, which is a
  2142. * string of comma separated values, or an Array of keys, or multiple keys.
  2143. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2144. */
  2145. }, {
  2146. key: "addAscending",
  2147. value: function ()
  2148. /*: ParseQuery*/
  2149. {
  2150. var _this9 = this;
  2151. if (!this._order) {
  2152. this._order = [];
  2153. }
  2154. for (var _len2 = arguments.length, keys = new Array(_len2), _key6 = 0; _key6 < _len2; _key6++) {
  2155. keys[_key6] = arguments[_key6];
  2156. }
  2157. (0, _forEach.default)(keys).call(keys, function (key) {
  2158. var _context16;
  2159. if ((0, _isArray.default)(key)) {
  2160. key = key.join();
  2161. }
  2162. _this9._order = (0, _concat.default)(_context16 = _this9._order).call(_context16, key.replace(/\s/g, '').split(','));
  2163. });
  2164. return this;
  2165. }
  2166. /**
  2167. * Sorts the results in descending order by the given key.
  2168. *
  2169. * @param {(string|string[])} keys The key to order by, which is a
  2170. * string of comma separated values, or an Array of keys, or multiple keys.
  2171. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2172. */
  2173. }, {
  2174. key: "descending",
  2175. value: function ()
  2176. /*: ParseQuery*/
  2177. {
  2178. this._order = [];
  2179. for (var _len3 = arguments.length, keys = new Array(_len3), _key7 = 0; _key7 < _len3; _key7++) {
  2180. keys[_key7] = arguments[_key7];
  2181. }
  2182. return this.addDescending.apply(this, keys);
  2183. }
  2184. /**
  2185. * Sorts the results in descending order by the given key,
  2186. * but can also add secondary sort descriptors without overwriting _order.
  2187. *
  2188. * @param {(string|string[])} keys The key to order by, which is a
  2189. * string of comma separated values, or an Array of keys, or multiple keys.
  2190. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2191. */
  2192. }, {
  2193. key: "addDescending",
  2194. value: function ()
  2195. /*: ParseQuery*/
  2196. {
  2197. var _this10 = this;
  2198. if (!this._order) {
  2199. this._order = [];
  2200. }
  2201. for (var _len4 = arguments.length, keys = new Array(_len4), _key8 = 0; _key8 < _len4; _key8++) {
  2202. keys[_key8] = arguments[_key8];
  2203. }
  2204. (0, _forEach.default)(keys).call(keys, function (key) {
  2205. var _context17, _context18;
  2206. if ((0, _isArray.default)(key)) {
  2207. key = key.join();
  2208. }
  2209. _this10._order = (0, _concat.default)(_context17 = _this10._order).call(_context17, (0, _map2.default)(_context18 = key.replace(/\s/g, '').split(',')).call(_context18, function (k) {
  2210. return "-".concat(k);
  2211. }));
  2212. });
  2213. return this;
  2214. }
  2215. /** Query Options * */
  2216. /**
  2217. * Sets the number of results to skip before returning any results.
  2218. * This is useful for pagination.
  2219. * Default is to skip zero results.
  2220. *
  2221. * @param {number} n the number of results to skip.
  2222. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2223. */
  2224. }, {
  2225. key: "skip",
  2226. value: function (n
  2227. /*: number*/
  2228. )
  2229. /*: ParseQuery*/
  2230. {
  2231. if (typeof n !== 'number' || n < 0) {
  2232. throw new Error('You can only skip by a positive number');
  2233. }
  2234. this._skip = n;
  2235. return this;
  2236. }
  2237. /**
  2238. * Sets the limit of the number of results to return. The default limit is 100.
  2239. *
  2240. * @param {number} n the number of results to limit to.
  2241. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2242. */
  2243. }, {
  2244. key: "limit",
  2245. value: function (n
  2246. /*: number*/
  2247. )
  2248. /*: ParseQuery*/
  2249. {
  2250. if (typeof n !== 'number') {
  2251. throw new Error('You can only set the limit to a numeric value');
  2252. }
  2253. this._limit = n;
  2254. return this;
  2255. }
  2256. /**
  2257. * Sets the flag to include with response the total number of objects satisfying this query,
  2258. * despite limits/skip. Might be useful for pagination.
  2259. * Note that result of this query will be wrapped as an object with
  2260. * `results`: holding {ParseObject} array and `count`: integer holding total number
  2261. *
  2262. * @param {boolean} includeCount false - disable, true - enable.
  2263. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2264. */
  2265. }, {
  2266. key: "withCount",
  2267. value: function ()
  2268. /*: ParseQuery*/
  2269. {
  2270. var includeCount
  2271. /*: boolean*/
  2272. = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  2273. if (typeof includeCount !== 'boolean') {
  2274. throw new Error('You can only set withCount to a boolean value');
  2275. }
  2276. this._count = includeCount;
  2277. return this;
  2278. }
  2279. /**
  2280. * Includes nested Parse.Objects for the provided key. You can use dot
  2281. * notation to specify which fields in the included object are also fetched.
  2282. *
  2283. * You can include all nested Parse.Objects by passing in '*'.
  2284. * Requires Parse Server 3.0.0+
  2285. * <pre>query.include('*');</pre>
  2286. *
  2287. * @param {...string|Array<string>} keys The name(s) of the key(s) to include.
  2288. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2289. */
  2290. }, {
  2291. key: "include",
  2292. value: function ()
  2293. /*: ParseQuery*/
  2294. {
  2295. var _this11 = this;
  2296. for (var _len5 = arguments.length, keys = new Array(_len5), _key9 = 0; _key9 < _len5; _key9++) {
  2297. keys[_key9] = arguments[_key9];
  2298. }
  2299. (0, _forEach.default)(keys).call(keys, function (key) {
  2300. if ((0, _isArray.default)(key)) {
  2301. var _context19;
  2302. _this11._include = (0, _concat.default)(_context19 = _this11._include).call(_context19, key);
  2303. } else {
  2304. _this11._include.push(key);
  2305. }
  2306. });
  2307. return this;
  2308. }
  2309. /**
  2310. * Includes all nested Parse.Objects.
  2311. *
  2312. * Requires Parse Server 3.0.0+
  2313. *
  2314. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2315. */
  2316. }, {
  2317. key: "includeAll",
  2318. value: function ()
  2319. /*: ParseQuery*/
  2320. {
  2321. return this.include('*');
  2322. }
  2323. /**
  2324. * Restricts the fields of the returned Parse.Objects to include only the
  2325. * provided keys. If this is called multiple times, then all of the keys
  2326. * specified in each of the calls will be included.
  2327. *
  2328. * @param {...string|Array<string>} keys The name(s) of the key(s) to include.
  2329. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2330. */
  2331. }, {
  2332. key: "select",
  2333. value: function ()
  2334. /*: ParseQuery*/
  2335. {
  2336. var _this12 = this;
  2337. if (!this._select) {
  2338. this._select = [];
  2339. }
  2340. for (var _len6 = arguments.length, keys = new Array(_len6), _key10 = 0; _key10 < _len6; _key10++) {
  2341. keys[_key10] = arguments[_key10];
  2342. }
  2343. (0, _forEach.default)(keys).call(keys, function (key) {
  2344. if ((0, _isArray.default)(key)) {
  2345. var _context20;
  2346. _this12._select = (0, _concat.default)(_context20 = _this12._select).call(_context20, key);
  2347. } else {
  2348. _this12._select.push(key);
  2349. }
  2350. });
  2351. return this;
  2352. }
  2353. /**
  2354. * Restricts the fields of the returned Parse.Objects to all keys except the
  2355. * provided keys. Exclude takes precedence over select and include.
  2356. *
  2357. * Requires Parse Server 3.6.0+
  2358. *
  2359. * @param {...string|Array<string>} keys The name(s) of the key(s) to exclude.
  2360. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2361. */
  2362. }, {
  2363. key: "exclude",
  2364. value: function ()
  2365. /*: ParseQuery*/
  2366. {
  2367. var _this13 = this;
  2368. for (var _len7 = arguments.length, keys = new Array(_len7), _key11 = 0; _key11 < _len7; _key11++) {
  2369. keys[_key11] = arguments[_key11];
  2370. }
  2371. (0, _forEach.default)(keys).call(keys, function (key) {
  2372. if ((0, _isArray.default)(key)) {
  2373. var _context21;
  2374. _this13._exclude = (0, _concat.default)(_context21 = _this13._exclude).call(_context21, key);
  2375. } else {
  2376. _this13._exclude.push(key);
  2377. }
  2378. });
  2379. return this;
  2380. }
  2381. /**
  2382. * Changes the read preference that the backend will use when performing the query to the database.
  2383. *
  2384. * @param {string} readPreference The read preference for the main query.
  2385. * @param {string} includeReadPreference The read preference for the queries to include pointers.
  2386. * @param {string} subqueryReadPreference The read preference for the sub queries.
  2387. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2388. */
  2389. }, {
  2390. key: "readPreference",
  2391. value: function (_readPreference
  2392. /*: string*/
  2393. , includeReadPreference
  2394. /*:: ?: string*/
  2395. , subqueryReadPreference
  2396. /*:: ?: string*/
  2397. )
  2398. /*: ParseQuery*/
  2399. {
  2400. this._readPreference = _readPreference;
  2401. this._includeReadPreference = includeReadPreference;
  2402. this._subqueryReadPreference = subqueryReadPreference;
  2403. return this;
  2404. }
  2405. }, {
  2406. key: "onChange",
  2407. value: function (onUpdate
  2408. /*: any*/
  2409. , onError
  2410. /*:: ?: any*/
  2411. /*:: ?: string*/
  2412. )
  2413. /*: Promise<LiveQuerySubscription>*/
  2414. {
  2415. var sub = null;
  2416. this.subscribe().then(function (subscription) {
  2417. sub = subscription;
  2418. subscription.on('create', function (object) {
  2419. onUpdate(object);
  2420. });
  2421. subscription.on('update', function (object) {
  2422. onUpdate(object);
  2423. });
  2424. subscription.on('error', function (err) {
  2425. if (onError) {
  2426. onError(err);
  2427. } else {
  2428. // eslint-disable-next-line no-console
  2429. console.warn('Subscription error', err);
  2430. }
  2431. });
  2432. }).catch(function (err) {
  2433. if (onError) {
  2434. onError(err);
  2435. } else {
  2436. // eslint-disable-next-line no-console
  2437. console.warn('Subscription connection error', err);
  2438. }
  2439. });
  2440. return function () {
  2441. if (sub) {
  2442. sub.unsubscribe();
  2443. }
  2444. };
  2445. }
  2446. /**
  2447. * Subscribe this query to get liveQuery updates
  2448. *
  2449. * @param {string} sessionToken (optional) Defaults to the currentUser
  2450. * @returns {Promise<LiveQuerySubscription>} Returns the liveQuerySubscription, it's an event emitter
  2451. * which can be used to get liveQuery updates.
  2452. */
  2453. }, {
  2454. key: "subscribe",
  2455. value: function () {
  2456. var _subscribe = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee7(sessionToken
  2457. /*:: ?: string*/
  2458. ) {
  2459. var currentUser, liveQueryClient, subscription;
  2460. return _regenerator.default.wrap(function (_context22) {
  2461. while (1) {
  2462. switch (_context22.prev = _context22.next) {
  2463. case 0:
  2464. _context22.next = 2;
  2465. return _CoreManager.default.getUserController().currentUserAsync();
  2466. case 2:
  2467. currentUser = _context22.sent;
  2468. if (!sessionToken) {
  2469. sessionToken = currentUser ? currentUser.getSessionToken() : undefined;
  2470. }
  2471. _context22.next = 6;
  2472. return _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient();
  2473. case 6:
  2474. liveQueryClient = _context22.sent;
  2475. if (liveQueryClient.shouldOpen()) {
  2476. liveQueryClient.open();
  2477. }
  2478. subscription = liveQueryClient.subscribe(this, sessionToken);
  2479. return _context22.abrupt("return", subscription.subscribePromise.then(function () {
  2480. return subscription;
  2481. }));
  2482. case 10:
  2483. case "end":
  2484. return _context22.stop();
  2485. }
  2486. }
  2487. }, _callee7, this);
  2488. }));
  2489. return function () {
  2490. return _subscribe.apply(this, arguments);
  2491. };
  2492. }()
  2493. /**
  2494. * Constructs a Parse.Query that is the OR of the passed in queries. For
  2495. * example:
  2496. * <pre>var compoundQuery = Parse.Query.or(query1, query2, query3);</pre>
  2497. *
  2498. * will create a compoundQuery that is an or of the query1, query2, and
  2499. * query3.
  2500. *
  2501. * @param {...Parse.Query} queries The list of queries to OR.
  2502. * @static
  2503. * @returns {Parse.Query} The query that is the OR of the passed in queries.
  2504. */
  2505. }, {
  2506. key: "fromNetwork",
  2507. value:
  2508. /**
  2509. * Change the source of this query to the server.
  2510. *
  2511. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2512. */
  2513. function ()
  2514. /*: ParseQuery*/
  2515. {
  2516. this._queriesLocalDatastore = false;
  2517. this._localDatastorePinName = null;
  2518. return this;
  2519. }
  2520. /**
  2521. * Changes the source of this query to all pinned objects.
  2522. *
  2523. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2524. */
  2525. }, {
  2526. key: "fromLocalDatastore",
  2527. value: function ()
  2528. /*: ParseQuery*/
  2529. {
  2530. return this.fromPinWithName(null);
  2531. }
  2532. /**
  2533. * Changes the source of this query to the default group of pinned objects.
  2534. *
  2535. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2536. */
  2537. }, {
  2538. key: "fromPin",
  2539. value: function ()
  2540. /*: ParseQuery*/
  2541. {
  2542. return this.fromPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
  2543. }
  2544. /**
  2545. * Changes the source of this query to a specific group of pinned objects.
  2546. *
  2547. * @param {string} name The name of query source.
  2548. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2549. */
  2550. }, {
  2551. key: "fromPinWithName",
  2552. value: function (name
  2553. /*:: ?: string*/
  2554. )
  2555. /*: ParseQuery*/
  2556. {
  2557. var localDatastore = _CoreManager.default.getLocalDatastore();
  2558. if (localDatastore.checkIfEnabled()) {
  2559. this._queriesLocalDatastore = true;
  2560. this._localDatastorePinName = name;
  2561. }
  2562. return this;
  2563. }
  2564. /**
  2565. * Cancels the current network request (if any is running).
  2566. *
  2567. * @returns {Parse.Query} Returns the query, so you can chain this call.
  2568. */
  2569. }, {
  2570. key: "cancel",
  2571. value: function ()
  2572. /*: ParseQuery*/
  2573. {
  2574. var _this14 = this;
  2575. if (this._xhrRequest.task && typeof this._xhrRequest.task.abort === 'function') {
  2576. this._xhrRequest.task._aborted = true;
  2577. this._xhrRequest.task.abort();
  2578. this._xhrRequest.task = null;
  2579. this._xhrRequest.onchange = function () {};
  2580. return this;
  2581. }
  2582. return this._xhrRequest.onchange = function () {
  2583. return _this14.cancel();
  2584. };
  2585. }
  2586. }, {
  2587. key: "_setRequestTask",
  2588. value: function (options) {
  2589. var _this15 = this;
  2590. options.requestTask = function (task) {
  2591. _this15._xhrRequest.task = task;
  2592. _this15._xhrRequest.onchange();
  2593. };
  2594. }
  2595. }], [{
  2596. key: "fromJSON",
  2597. value: function (className
  2598. /*: string*/
  2599. , json
  2600. /*: QueryJSON*/
  2601. )
  2602. /*: ParseQuery*/
  2603. {
  2604. var query = new ParseQuery(className);
  2605. return query.withJSON(json);
  2606. }
  2607. }, {
  2608. key: "or",
  2609. value: function ()
  2610. /*: ParseQuery*/
  2611. {
  2612. for (var _len8 = arguments.length, queries = new Array(_len8), _key12 = 0; _key12 < _len8; _key12++) {
  2613. queries[_key12] = arguments[_key12];
  2614. }
  2615. var className = _getClassNameFromQueries(queries);
  2616. var query = new ParseQuery(className);
  2617. query._orQuery(queries);
  2618. return query;
  2619. }
  2620. /**
  2621. * Constructs a Parse.Query that is the AND of the passed in queries. For
  2622. * example:
  2623. * <pre>var compoundQuery = Parse.Query.and(query1, query2, query3);</pre>
  2624. *
  2625. * will create a compoundQuery that is an and of the query1, query2, and
  2626. * query3.
  2627. *
  2628. * @param {...Parse.Query} queries The list of queries to AND.
  2629. * @static
  2630. * @returns {Parse.Query} The query that is the AND of the passed in queries.
  2631. */
  2632. }, {
  2633. key: "and",
  2634. value: function ()
  2635. /*: ParseQuery*/
  2636. {
  2637. for (var _len9 = arguments.length, queries = new Array(_len9), _key13 = 0; _key13 < _len9; _key13++) {
  2638. queries[_key13] = arguments[_key13];
  2639. }
  2640. var className = _getClassNameFromQueries(queries);
  2641. var query = new ParseQuery(className);
  2642. query._andQuery(queries);
  2643. return query;
  2644. }
  2645. /**
  2646. * Constructs a Parse.Query that is the NOR of the passed in queries. For
  2647. * example:
  2648. * <pre>const compoundQuery = Parse.Query.nor(query1, query2, query3);</pre>
  2649. *
  2650. * will create a compoundQuery that is a nor of the query1, query2, and
  2651. * query3.
  2652. *
  2653. * @param {...Parse.Query} queries The list of queries to NOR.
  2654. * @static
  2655. * @returns {Parse.Query} The query that is the NOR of the passed in queries.
  2656. */
  2657. }, {
  2658. key: "nor",
  2659. value: function ()
  2660. /*: ParseQuery*/
  2661. {
  2662. for (var _len10 = arguments.length, queries = new Array(_len10), _key14 = 0; _key14 < _len10; _key14++) {
  2663. queries[_key14] = arguments[_key14];
  2664. }
  2665. var className = _getClassNameFromQueries(queries);
  2666. var query = new ParseQuery(className);
  2667. query._norQuery(queries);
  2668. return query;
  2669. }
  2670. }]);
  2671. return ParseQuery;
  2672. }();
  2673. var DefaultController = {
  2674. find: function (className
  2675. /*: string*/
  2676. , params
  2677. /*: QueryJSON*/
  2678. , options
  2679. /*: RequestOptions*/
  2680. )
  2681. /*: Promise<Array<ParseObject>>*/
  2682. {
  2683. var RESTController = _CoreManager.default.getRESTController();
  2684. return RESTController.request('GET', "classes/".concat(className), params, options);
  2685. },
  2686. aggregate: function (className
  2687. /*: string*/
  2688. , params
  2689. /*: any*/
  2690. , options
  2691. /*: RequestOptions*/
  2692. )
  2693. /*: Promise<Array<mixed>>*/
  2694. {
  2695. var RESTController = _CoreManager.default.getRESTController();
  2696. return RESTController.request('GET', "aggregate/".concat(className), params, options);
  2697. }
  2698. };
  2699. _CoreManager.default.setQueryController(DefaultController);
  2700. var _default = ParseQuery;
  2701. exports.default = _default;