All files / utils LocalStoragePlus.ts

91.49% Statements 43/47
93.33% Branches 28/30
84.62% Functions 22/26
91.11% Lines 41/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267                                                                23x           23x               53x 17x 8x   1x 1x 5x 5x 5x     1x                         23x               73x                             17x 17x   17x 17x                                       53x   53x 53x 53x 35x   35x       6x     29x       18x                   6x                 3x             1x 5x 5x                                 5x   5x                                 5x   5x                                 4x                 28x                 2x             2x                   4x                   4x      
import { JsonValue } from '../types'
import { inMiniProgram } from './inMiniProgram'
 
export interface LocalStoragePlusOptions {
  /** 存储键 */
  key: string
}
 
export interface LocalStoragePlusSetOptions {
  /** 存活时间(毫秒) */
  ttl?: number
 
  /** 标签 */
  tag?: string | number
}
 
export interface LocalStoragePlusGetOptions {
  /** 标签 */
  tag?: string | number
}
 
interface LocalStoragePlusRawData<T> {
  /** 存储值 */
  v: T
 
  /** 过期时间(毫秒时间戳) */
  e?: number
 
  /** 标签 */
  t?: string | number
}
 
const mp = inMiniProgram()
const storage: {
  get: (key: string) => string | null
  set: (key: string, value: string) => void
  remove: (key: string) => void
  keys: () => string[]
} = mp
  ? {
      get: key => mp.getStorageSync(key),
      set: (key, value) => mp.setStorageSync(key, value),
      remove: key => mp.removeStorageSync(key),
      keys: () => mp.getStorageInfoSync().keys,
    }
  : {
      get: key => localStorage.getItem(key),
      set: (key, value) => localStorage.setItem(key, value),
      remove: key => localStorage.removeItem(key),
      keys: () => {
        const keys: string[] = []
        for (let i = 0, len = localStorage.length; i < len; i++) {
          const key = localStorage.key(i)
          if (key != null) {
            keys.push(key)
          }
        }
        return keys
      },
    }
 
/**
 * 本地存储增强。
 *
 * 已兼容小程序。
 */
export class LocalStoragePlus<T extends JsonValue> {
  /**
   * 本地存储键名前缀。
   */
  private static prefix = 'LSP:'
 
  /**
   * 获取完全的键名。
   *
   * @param key 键名
   */
  private static getFullKey(key: string): string {
    return `${this.prefix}${key}`
  }
 
  /**
   * 设置本地存储。
   *
   * @param key 键
   * @param value 值
   * @param options 选项
   */
  static set<T extends JsonValue>(
    key: string,
    value: T | ((prevValue: T | null) => T),
    options?: LocalStoragePlusSetOptions,
  ): void {
    const { ttl, tag } = options || {}
    const expiredAt = ttl && Date.now() + ttl
    const nextValue =
      typeof value === 'function' ? value(this.get<T>(key, { tag })) : value
    storage.set(
      this.getFullKey(key),
      JSON.stringify({
        v: nextValue,
        e: expiredAt,
        t: tag,
      } as LocalStoragePlusRawData<T>),
    )
  }
 
  /**
   * 获取本地存储。
   *
   * @param key 键
   * @param options 选项
   */
  static get<T extends JsonValue>(
    key: string,
    options?: LocalStoragePlusGetOptions,
  ): T | null {
    const { tag } = options || {}
 
    try {
      const rawText = storage.get(this.getFullKey(key))
      if (rawText != null) {
        const rawData = JSON.parse(rawText) as LocalStoragePlusRawData<T>
 
        if (
          (tag != null && rawData.t !== tag) ||
          (rawData.e != null && rawData.e < Date.now())
        ) {
          return null
        }
 
        return rawData.v
      }
    } catch {}
 
    return null
  }
 
  /**
   * 是否存在本地存储。
   *
   * @param key 键
   * @param options 选项
   */
  static has(key: string, options?: LocalStoragePlusGetOptions): boolean {
    return this.get(key, options) !== null
  }
 
  /**
   * 删除本地存储。
   *
   * @param key 键
   */
  static remove(key: string): void {
    storage.remove(this.getFullKey(key))
  }
 
  /**
   * 清空本地存储。
   */
  static clear(): void {
    storage.keys().forEach(key => {
      if (key.indexOf(this.prefix) === 0) {
        storage.remove(key)
      }
    })
  }
 
  /**
   * 将本地存储的值增加给定值,若本地存储不存在,则初始化为 `0` 后操作。
   *
   * @param key 键
   * @param value 增加值,默认 `1`
   * @param options 选项
   */
  static increase(
    key: string,
    value = 1,
    options?: LocalStoragePlusSetOptions,
  ): void {
    this.set(
      key,
      (prevValue: number | null) => Number(prevValue || 0) + value,
      options,
    )
  }
 
  /**
   * 将本地存储的值减少给定值,若本地存储不存在,则初始化为 `0` 后操作。
   *
   * @param key 键
   * @param value 减小值,默认 `1`
   * @param options 选项
   */
  static decrease(
    key: string,
    value = 1,
    options?: LocalStoragePlusSetOptions,
  ): void {
    this.set(
      key,
      (prevValue: number | null) => Number(prevValue || 0) - value,
      options,
    )
  }
 
  constructor(private options: LocalStoragePlusOptions) {}
 
  /**
   * 设置值。
   *
   * @param value 值
   * @param options 选项
   */
  set(
    value: T | ((prevValue: T | null) => T),
    options?: LocalStoragePlusSetOptions,
  ): void {
    return LocalStoragePlus.set<T>(this.options.key, value, options)
  }
 
  /**
   * 获取值。
   *
   * @param options 选项
   */
  get(options?: LocalStoragePlusGetOptions): T | null {
    return LocalStoragePlus.get(this.options.key, options)
  }
 
  /**
   * 是否存在值。
   *
   * @param options 选项
   */
  has(options?: LocalStoragePlusGetOptions): boolean {
    return LocalStoragePlus.has(this.options.key, options)
  }
 
  /**
   * 删除值。
   */
  remove(): void {
    return LocalStoragePlus.remove(this.options.key)
  }
 
  /**
   * 自增。
   *
   * @param value 增加值
   * @param options 选项
   */
  increase(value = 1, options?: LocalStoragePlusSetOptions): void {
    return LocalStoragePlus.increase(this.options.key, value, options)
  }
 
  /**
   * 自减。
   *
   * @param value 减少值
   * @param options 选项
   */
  decrease(value = 1, options?: LocalStoragePlusSetOptions): void {
    return LocalStoragePlus.decrease(this.options.key, value, options)
  }
}