LocalDatastore.js 13 KB

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