SimpleLocalDataStorage.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { onMounted, ref, type Ref } from "vue";
  2. export function useSimpleLocalDataStorage<T>(
  3. subKey: string,
  4. requireValueAtLoad = false,
  5. defaultValue: T|null = null,
  6. ) {
  7. const key = `SimpleLocalDataStorage.${subKey}`;
  8. async function get() : Promise<T | null> {
  9. try {
  10. const res = await uni.getStorage({ key });
  11. if (res.data)
  12. return JSON.parse(res.data) as T;
  13. } catch (e) {
  14. console.error(e);
  15. }
  16. return defaultValue ?? null;
  17. }
  18. async function set(newValue: T|null) {
  19. if (newValue === null)
  20. await uni.removeStorage({ key });
  21. else
  22. await uni.setStorage({ key, data: JSON.stringify(newValue) });
  23. value.value = newValue;
  24. }
  25. async function update(fn: (oldValue: T|null) => T|null) {
  26. const oldValue = await get();
  27. const newValue = fn(oldValue);
  28. await set(newValue);
  29. return newValue;
  30. }
  31. const value = ref<T|null>(defaultValue) as Ref<T|null>;
  32. onMounted(async () => {
  33. if (requireValueAtLoad)
  34. value.value = await get() as T;
  35. })
  36. return {
  37. get,
  38. set,
  39. update,
  40. value,
  41. }
  42. }
  43. export function useSimpleLocalArrayDataStorage<T>(
  44. subKey: string,
  45. requireValueAtLoad = false,
  46. defaultValue: T[]|null = null,
  47. ) {
  48. const {
  49. value,
  50. get,
  51. set,
  52. update,
  53. } = useSimpleLocalDataStorage<T[]>(subKey, requireValueAtLoad, defaultValue);
  54. async function arrayRemove(index: number) {
  55. return await update((a) => {
  56. if (a instanceof Array)
  57. return a.filter((_, i) => i !== index);
  58. return a;
  59. });
  60. }
  61. async function arrayPush(newItem: T) {
  62. return await update((a) => {
  63. if (a instanceof Array) {
  64. a.push(newItem);
  65. return a;
  66. }
  67. return a;
  68. });
  69. }
  70. async function arrayUpdate(index: number, updateItem: (old: T) => T) {
  71. return await update((a) => {
  72. if (a instanceof Array) {
  73. a[index] = updateItem(a[index]);
  74. return a;
  75. }
  76. return a;
  77. });
  78. }
  79. return {
  80. get,
  81. set,
  82. update,
  83. arrayRemove,
  84. arrayPush,
  85. arrayUpdate,
  86. value,
  87. }
  88. }