Skip to content

Commit

Permalink
fix(browser): 修复常作为顶层方法导出 的LocalStorageCache `createLocalStorageCac…
Browse files Browse the repository at this point in the history
…he` `SessionStorageCache` `createSessionStorageCache` 这些方法在 ssr 环境报错的问题
  • Loading branch information
Colourlessglow committed May 3, 2024
1 parent fe13062 commit 06dff1b
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 14 deletions.
12 changes: 2 additions & 10 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,10 @@ dist
.npmrc
.cache

packages/*/dist
packages/*/.turbo

legacy/*/dist
legacy/*/.turbo
dist
.turbo

!docs/.vitepress/dist
docs/.vitepress/cache
.local
# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
Expand Down
4 changes: 2 additions & 2 deletions packages/broswer/src/cache/localStorage.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { StorageCache, StorageCacheStoreParseType } from './storage'
import { StorageCache, StorageCacheStoreParseType, fallbackStorage } from './storage'

/**
* localStorage缓存商店
*/
export class LocalStorageCache<T = any> extends StorageCache<T> {
constructor(key: string, parse?: StorageCacheStoreParseType<T> | true) {
super(window.localStorage, key, parse)
super(window?.localStorage || fallbackStorage, key, parse)
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/broswer/src/cache/sessionStorage.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { StorageCache, StorageCacheStoreParseType } from './storage'
import { StorageCache, StorageCacheStoreParseType, fallbackStorage } from './storage'

/**
* sessionStorage缓存商店
*/
export class SessionStorageCache<T = any> extends StorageCache<T> {
constructor(key: string, parse?: StorageCacheStoreParseType<T> | true) {
super(window.sessionStorage, key, parse)
super(window?.sessionStorage || fallbackStorage, key, parse)
}
}

Expand Down
17 changes: 17 additions & 0 deletions packages/broswer/src/cache/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,23 @@ const JSONStorageCacheStoreParse = {
set: (value) => JSON.stringify(value),
}

/**
* 一个如果当前平台不存在 `Storage` 的实现时的,后备选项
* 主要为了兼容 ssr
*/
export const fallbackStorage: Storage = {
length: 0,
clear() {},
getItem() {
return null
},
key() {
return null
},
removeItem() {},
setItem() {},
}

/**
* Storage缓存商店
* 提供自动json数据处理功能
Expand Down

0 comments on commit 06dff1b

Please sign in to comment.