LocalDatastore.js 12 KB

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