快应用下模拟同步Stroage APi

快应用没有strorageXxxSync,它们需要一些巧妙的方法进行模拟。但即使这样,我们也需要你在打开每个页面上初始化一下这个方法。

ReactQuick.js中的实现

  1. const storage = require('@system.storage')
  2. import { noop } from 'react-core/util'
  3. function saveParse (str) {
  4. try {
  5. return JSON.parse(str)
  6. } catch (err) {
  7. // eslint-disable-line
  8. }
  9. return str
  10. }
  11. function setStorage ({ key, data, success, fail = noop, complete }) {
  12. let value = data
  13. if (typeof value === 'object') {
  14. try {
  15. value = JSON.stringify(value)
  16. } catch (error) {
  17. return fail(error)
  18. }
  19. }
  20. storage.set({ key, value, success, fail, complete})
  21. }
  22. function getStorage ({ key, success, fail, complete }) {
  23. function dataObj (data) {
  24. success({
  25. data: saveParse(data)
  26. })
  27. }
  28. storage.get({ key, success: dataObj, fail, complete})
  29. }
  30. function removeStorage (obj) {
  31. storage.delete(obj)
  32. }
  33. function clearStorage (obj) {
  34. storage.clear(obj)
  35. }
  36. var initStorage = false
  37. export function initStorageSync (storageCache) {
  38. if (typeof ReactQuick !== 'object') {
  39. return
  40. }
  41. var apis = ReactQuick.api; // eslint-disable-line
  42. var n = storage.length
  43. var j = 0
  44. for (var i = 0; i < n; i++) {
  45. storage.key({
  46. index: i,
  47. success: function (key) {
  48. storage.get({
  49. key: key,
  50. success: function (value) {
  51. storageCache[key] = value
  52. if (++j == n) {
  53. console.log('init storage success')
  54. }
  55. }
  56. })
  57. }
  58. })
  59. }
  60. apis.setStorageSync = function (key, value) {
  61. setStorage({
  62. key: key,
  63. data: value
  64. })
  65. return storageCache[key] = value
  66. }
  67. apis.getStorageSync = function (key) {
  68. return saveParse(storageCache[key])
  69. }
  70. apis.removeStorageSync = function (key) {
  71. delete storageCache[key]
  72. removeStorage({key: key})
  73. }
  74. apis.clearStorageSync = function () {
  75. for (var i in storageCache) {
  76. delete storageCache[i]
  77. }
  78. clearStorage({})
  79. }
  80. }
  81. function warnToInitStorage () {
  82. if (!initStorage) {
  83. console.log('还没有初始化storageSync'); // eslint-disable-line
  84. }
  85. }
  86. export var setStorageSync = warnToInitStorage
  87. export var getStorageSync = warnToInitStorage
  88. export var removeStorageSync = warnToInitStorage
  89. export var clearStorageSync = warnToInitStorage
  90. export { setStorage, getStorage, removeStorage, clearStorage }

app.js这样初始化它, 因为快应用是一个多页应用,不是SPA,只有globalData中的数据在每次页面打开时不会清空,globalData.__storage作为一个缓存可以加快我们读写的速度。

  1. globalData = {
  2. ufo: 'ufo'
  3. __storage: {}
  4. };
  5. onGlobalLoad() {
  6. if (process.env.ANU_ENV === 'quick') {
  7. React.api.initStorageSync(this.globalData.__storage);
  8. }
  9. }