LocalDatastore.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));
  9. var _set = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/set"));
  10. var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));
  11. var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));
  12. var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/includes"));
  13. var _startsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/starts-with"));
  14. var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array"));
  15. var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));
  16. var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));
  17. var _from = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/from"));
  18. var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find"));
  19. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  20. var _LocalDatastoreController = _interopRequireDefault(require("./LocalDatastoreController"));
  21. var _ParseQuery = _interopRequireDefault(require("./ParseQuery"));
  22. var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
  23. /**
  24. * Provides a local datastore which can be used to store and retrieve <code>Parse.Object</code>. <br />
  25. * To enable this functionality, call <code>Parse.enableLocalDatastore()</code>.
  26. *
  27. * Pin object to add to local datastore
  28. *
  29. * <pre>await object.pin();</pre>
  30. * <pre>await object.pinWithName('pinName');</pre>
  31. *
  32. * Query pinned objects
  33. *
  34. * <pre>query.fromLocalDatastore();</pre>
  35. * <pre>query.fromPin();</pre>
  36. * <pre>query.fromPinWithName();</pre>
  37. *
  38. * <pre>const localObjects = await query.find();</pre>
  39. *
  40. * @class Parse.LocalDatastore
  41. * @static
  42. */
  43. const LocalDatastore = {
  44. isEnabled: false,
  45. isSyncing: false,
  46. fromPinWithName(name) {
  47. const controller = _CoreManager.default.getLocalDatastoreController();
  48. return controller.fromPinWithName(name);
  49. },
  50. async pinWithName(name, value) {
  51. const controller = _CoreManager.default.getLocalDatastoreController();
  52. return controller.pinWithName(name, value);
  53. },
  54. async unPinWithName(name) {
  55. const controller = _CoreManager.default.getLocalDatastoreController();
  56. return controller.unPinWithName(name);
  57. },
  58. _getAllContents() {
  59. const controller = _CoreManager.default.getLocalDatastoreController();
  60. return controller.getAllContents();
  61. },
  62. // Use for testing
  63. async _getRawStorage() {
  64. const controller = _CoreManager.default.getLocalDatastoreController();
  65. return controller.getRawStorage();
  66. },
  67. async _clear() {
  68. const controller = _CoreManager.default.getLocalDatastoreController();
  69. return controller.clear();
  70. },
  71. // Pin the object and children recursively
  72. // Saves the object and children key to Pin Name
  73. async _handlePinAllWithName(name, objects) {
  74. const pinName = this.getPinName(name);
  75. const toPinPromises = [];
  76. const objectKeys = [];
  77. for (const parent of objects) {
  78. const children = this._getChildren(parent);
  79. const parentKey = this.getKeyForObject(parent);
  80. const json = parent._toFullJSON(undefined, true);
  81. if (parent._localId) {
  82. json._localId = parent._localId;
  83. }
  84. children[parentKey] = json;
  85. for (const objectKey in children) {
  86. objectKeys.push(objectKey);
  87. toPinPromises.push(this.pinWithName(objectKey, [children[objectKey]]));
  88. }
  89. }
  90. const fromPinPromise = this.fromPinWithName(pinName);
  91. const [pinned] = await _promise.default.all([fromPinPromise, toPinPromises]);
  92. const toPin = [...new _set.default([...(pinned || []), ...objectKeys])];
  93. return this.pinWithName(pinName, toPin);
  94. },
  95. // Removes object and children keys from pin name
  96. // Keeps the object and children pinned
  97. async _handleUnPinAllWithName(name, objects) {
  98. const localDatastore = await this._getAllContents();
  99. const pinName = this.getPinName(name);
  100. const promises = [];
  101. let objectKeys = [];
  102. for (const parent of objects) {
  103. const children = this._getChildren(parent);
  104. const parentKey = this.getKeyForObject(parent);
  105. objectKeys.push(parentKey, ...(0, _keys.default)(children));
  106. }
  107. objectKeys = [...new _set.default(objectKeys)];
  108. let pinned = localDatastore[pinName] || [];
  109. pinned = (0, _filter.default)(pinned).call(pinned, item => !(0, _includes.default)(objectKeys).call(objectKeys, item));
  110. if (pinned.length == 0) {
  111. promises.push(this.unPinWithName(pinName));
  112. delete localDatastore[pinName];
  113. } else {
  114. promises.push(this.pinWithName(pinName, pinned));
  115. localDatastore[pinName] = pinned;
  116. }
  117. for (const objectKey of objectKeys) {
  118. let hasReference = false;
  119. for (const key in localDatastore) {
  120. if (key === _LocalDatastoreUtils.DEFAULT_PIN || (0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.PIN_PREFIX)) {
  121. const pinnedObjects = localDatastore[key] || [];
  122. if ((0, _includes.default)(pinnedObjects).call(pinnedObjects, objectKey)) {
  123. hasReference = true;
  124. break;
  125. }
  126. }
  127. }
  128. if (!hasReference) {
  129. promises.push(this.unPinWithName(objectKey));
  130. }
  131. }
  132. return _promise.default.all(promises);
  133. },
  134. // Retrieve all pointer fields from object recursively
  135. _getChildren(object) {
  136. const encountered = {};
  137. const json = object._toFullJSON(undefined, true);
  138. for (const key in json) {
  139. if (json[key] && json[key].__type && json[key].__type === 'Object') {
  140. this._traverse(json[key], encountered);
  141. }
  142. }
  143. return encountered;
  144. },
  145. _traverse(object, encountered) {
  146. if (!object.objectId) {
  147. return;
  148. } else {
  149. const objectKey = this.getKeyForObject(object);
  150. if (encountered[objectKey]) {
  151. return;
  152. }
  153. encountered[objectKey] = object;
  154. }
  155. for (const key in object) {
  156. let json = object[key];
  157. if (!object[key]) {
  158. json = object;
  159. }
  160. if (json.__type && json.__type === 'Object') {
  161. this._traverse(json, encountered);
  162. }
  163. }
  164. },
  165. // Transform keys in pin name to objects
  166. async _serializeObjectsFromPinName(name) {
  167. var _context;
  168. const localDatastore = await this._getAllContents();
  169. const allObjects = [];
  170. for (const key in localDatastore) {
  171. if ((0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.OBJECT_PREFIX)) {
  172. allObjects.push(localDatastore[key][0]);
  173. }
  174. }
  175. if (!name) {
  176. return allObjects;
  177. }
  178. const pinName = this.getPinName(name);
  179. const pinned = localDatastore[pinName];
  180. if (!(0, _isArray.default)(pinned)) {
  181. return [];
  182. }
  183. const promises = (0, _map.default)(pinned).call(pinned, objectKey => this.fromPinWithName(objectKey));
  184. let objects = await _promise.default.all(promises);
  185. objects = (0, _concat.default)(_context = []).call(_context, ...objects);
  186. return (0, _filter.default)(objects).call(objects, object => object != null);
  187. },
  188. // Replaces object pointers with pinned pointers
  189. // The object pointers may contain old data
  190. // Uses Breadth First Search Algorithm
  191. async _serializeObject(objectKey, localDatastore) {
  192. let LDS = localDatastore;
  193. if (!LDS) {
  194. LDS = await this._getAllContents();
  195. }
  196. if (!LDS[objectKey] || LDS[objectKey].length === 0) {
  197. return null;
  198. }
  199. const root = LDS[objectKey][0];
  200. const queue = [];
  201. const meta = {};
  202. let uniqueId = 0;
  203. meta[uniqueId] = root;
  204. queue.push(uniqueId);
  205. while (queue.length !== 0) {
  206. const nodeId = queue.shift();
  207. const subTreeRoot = meta[nodeId];
  208. for (const field in subTreeRoot) {
  209. const value = subTreeRoot[field];
  210. if (value.__type && value.__type === 'Object') {
  211. const key = this.getKeyForObject(value);
  212. if (LDS[key] && LDS[key].length > 0) {
  213. const pointer = LDS[key][0];
  214. uniqueId++;
  215. meta[uniqueId] = pointer;
  216. subTreeRoot[field] = pointer;
  217. queue.push(uniqueId);
  218. }
  219. }
  220. }
  221. }
  222. return root;
  223. },
  224. // Called when an object is save / fetched
  225. // Update object pin value
  226. async _updateObjectIfPinned(object) {
  227. if (!this.isEnabled) {
  228. return;
  229. }
  230. const objectKey = this.getKeyForObject(object);
  231. const pinned = await this.fromPinWithName(objectKey);
  232. if (!pinned || pinned.length === 0) {
  233. return;
  234. }
  235. return this.pinWithName(objectKey, [object._toFullJSON()]);
  236. },
  237. // Called when object is destroyed
  238. // Unpin object and remove all references from pin names
  239. // TODO: Destroy children?
  240. async _destroyObjectIfPinned(object) {
  241. if (!this.isEnabled) {
  242. return;
  243. }
  244. const localDatastore = await this._getAllContents();
  245. const objectKey = this.getKeyForObject(object);
  246. const pin = localDatastore[objectKey];
  247. if (!pin) {
  248. return;
  249. }
  250. const promises = [this.unPinWithName(objectKey)];
  251. delete localDatastore[objectKey];
  252. for (const key in localDatastore) {
  253. if (key === _LocalDatastoreUtils.DEFAULT_PIN || (0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.PIN_PREFIX)) {
  254. let pinned = localDatastore[key] || [];
  255. if ((0, _includes.default)(pinned).call(pinned, objectKey)) {
  256. pinned = (0, _filter.default)(pinned).call(pinned, item => item !== objectKey);
  257. if (pinned.length == 0) {
  258. promises.push(this.unPinWithName(key));
  259. delete localDatastore[key];
  260. } else {
  261. promises.push(this.pinWithName(key, pinned));
  262. localDatastore[key] = pinned;
  263. }
  264. }
  265. }
  266. }
  267. return _promise.default.all(promises);
  268. },
  269. // Update pin and references of the unsaved object
  270. async _updateLocalIdForObject(localId, object) {
  271. if (!this.isEnabled) {
  272. return;
  273. }
  274. const localKey = `${_LocalDatastoreUtils.OBJECT_PREFIX}${object.className}_${localId}`;
  275. const objectKey = this.getKeyForObject(object);
  276. const unsaved = await this.fromPinWithName(localKey);
  277. if (!unsaved || unsaved.length === 0) {
  278. return;
  279. }
  280. const promises = [this.unPinWithName(localKey), this.pinWithName(objectKey, unsaved)];
  281. const localDatastore = await this._getAllContents();
  282. for (const key in localDatastore) {
  283. if (key === _LocalDatastoreUtils.DEFAULT_PIN || (0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.PIN_PREFIX)) {
  284. let pinned = localDatastore[key] || [];
  285. if ((0, _includes.default)(pinned).call(pinned, localKey)) {
  286. pinned = (0, _filter.default)(pinned).call(pinned, item => item !== localKey);
  287. pinned.push(objectKey);
  288. promises.push(this.pinWithName(key, pinned));
  289. localDatastore[key] = pinned;
  290. }
  291. }
  292. }
  293. return _promise.default.all(promises);
  294. },
  295. /**
  296. * Updates Local Datastore from Server
  297. *
  298. * <pre>
  299. * await Parse.LocalDatastore.updateFromServer();
  300. * </pre>
  301. *
  302. * @function updateFromServer
  303. * @name Parse.LocalDatastore.updateFromServer
  304. * @static
  305. */
  306. async updateFromServer() {
  307. var _context2;
  308. if (!this.checkIfEnabled() || this.isSyncing) {
  309. return;
  310. }
  311. const localDatastore = await this._getAllContents();
  312. const keys = [];
  313. for (const key in localDatastore) {
  314. if ((0, _startsWith.default)(key).call(key, _LocalDatastoreUtils.OBJECT_PREFIX)) {
  315. keys.push(key);
  316. }
  317. }
  318. if (keys.length === 0) {
  319. return;
  320. }
  321. this.isSyncing = true;
  322. const pointersHash = {};
  323. for (const key of keys) {
  324. // Ignore the OBJECT_PREFIX
  325. let [,, className, objectId] = key.split('_');
  326. // User key is split into [ 'Parse', 'LDS', '', 'User', 'objectId' ]
  327. if (key.split('_').length === 5 && key.split('_')[3] === 'User') {
  328. className = '_User';
  329. objectId = key.split('_')[4];
  330. }
  331. if ((0, _startsWith.default)(objectId).call(objectId, 'local')) {
  332. continue;
  333. }
  334. if (!(className in pointersHash)) {
  335. pointersHash[className] = new _set.default();
  336. }
  337. pointersHash[className].add(objectId);
  338. }
  339. const queryPromises = (0, _map.default)(_context2 = (0, _keys.default)(pointersHash)).call(_context2, className => {
  340. const objectIds = (0, _from.default)(pointersHash[className]);
  341. const query = new _ParseQuery.default(className);
  342. query.limit(objectIds.length);
  343. if (objectIds.length === 1) {
  344. query.equalTo('objectId', objectIds[0]);
  345. } else {
  346. query.containedIn('objectId', objectIds);
  347. }
  348. return (0, _find.default)(query).call(query);
  349. });
  350. try {
  351. const responses = await _promise.default.all(queryPromises);
  352. const objects = (0, _concat.default)([]).apply([], responses);
  353. const pinPromises = (0, _map.default)(objects).call(objects, object => {
  354. const objectKey = this.getKeyForObject(object);
  355. return this.pinWithName(objectKey, object._toFullJSON());
  356. });
  357. await _promise.default.all(pinPromises);
  358. this.isSyncing = false;
  359. } catch (error) {
  360. console.error('Error syncing LocalDatastore: ', error);
  361. this.isSyncing = false;
  362. }
  363. },
  364. getKeyForObject(object) {
  365. const objectId = object.objectId || object._getId();
  366. return `${_LocalDatastoreUtils.OBJECT_PREFIX}${object.className}_${objectId}`;
  367. },
  368. getPinName(pinName) {
  369. if (!pinName || pinName === _LocalDatastoreUtils.DEFAULT_PIN) {
  370. return _LocalDatastoreUtils.DEFAULT_PIN;
  371. }
  372. return _LocalDatastoreUtils.PIN_PREFIX + pinName;
  373. },
  374. checkIfEnabled() {
  375. if (!this.isEnabled) {
  376. console.error('Parse.enableLocalDatastore() must be called first');
  377. }
  378. return this.isEnabled;
  379. }
  380. };
  381. module.exports = LocalDatastore;
  382. var _default = exports.default = LocalDatastore;
  383. _CoreManager.default.setLocalDatastoreController(_LocalDatastoreController.default);
  384. _CoreManager.default.setLocalDatastore(LocalDatastore);