LocalDatastoreController.browser.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /**
  2. * Copyright (c) 2015-present, Parse, LLC.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. * @flow
  10. */
  11. /* global localStorage */
  12. import { isLocalDatastoreKey } from './LocalDatastoreUtils';
  13. const LocalDatastoreController = {
  14. fromPinWithName(name
  15. /*: string*/
  16. )
  17. /*: Array<Object>*/
  18. {
  19. const values = localStorage.getItem(name);
  20. if (!values) {
  21. return [];
  22. }
  23. const objects = JSON.parse(values);
  24. return objects;
  25. },
  26. pinWithName(name
  27. /*: string*/
  28. , value
  29. /*: any*/
  30. ) {
  31. try {
  32. const values = JSON.stringify(value);
  33. localStorage.setItem(name, values);
  34. } catch (e) {
  35. // Quota exceeded, possibly due to Safari Private Browsing mode
  36. console.log(e.message);
  37. }
  38. },
  39. unPinWithName(name
  40. /*: string*/
  41. ) {
  42. localStorage.removeItem(name);
  43. },
  44. getAllContents()
  45. /*: Object*/
  46. {
  47. const LDS = {};
  48. for (let i = 0; i < localStorage.length; i += 1) {
  49. const key = localStorage.key(i);
  50. if (isLocalDatastoreKey(key)) {
  51. const value = localStorage.getItem(key);
  52. try {
  53. LDS[key] = JSON.parse(value);
  54. } catch (error) {
  55. console.error('Error getAllContents: ', error);
  56. }
  57. }
  58. }
  59. return LDS;
  60. },
  61. getRawStorage()
  62. /*: Object*/
  63. {
  64. const storage = {};
  65. for (let i = 0; i < localStorage.length; i += 1) {
  66. const key = localStorage.key(i);
  67. const value = localStorage.getItem(key);
  68. storage[key] = value;
  69. }
  70. return storage;
  71. },
  72. clear()
  73. /*: Promise*/
  74. {
  75. const toRemove = [];
  76. for (let i = 0; i < localStorage.length; i += 1) {
  77. const key = localStorage.key(i);
  78. if (isLocalDatastoreKey(key)) {
  79. toRemove.push(key);
  80. }
  81. }
  82. const promises = toRemove.map(this.unPinWithName);
  83. return Promise.all(promises);
  84. }
  85. };
  86. module.exports = LocalDatastoreController;