Skip to content

Instantly share code, notes, and snippets.

@tsmd
Created February 1, 2020 11:21
Show Gist options
  • Save tsmd/6397875dcf9523f1d5dcb918b4c354b8 to your computer and use it in GitHub Desktop.
Save tsmd/6397875dcf9523f1d5dcb918b4c354b8 to your computer and use it in GitHub Desktop.
localStorage, sessionStorage のごく薄いラッパー。Cookie 無効環境でストレージにアクセスしたときに発生する例外を捕捉しスクリプトが止まらないようにする。
/**
* @fileOverview
* localStorage, sessionStorage のごく薄いラッパー。
* Cookie 無効環境でストレージにアクセスしたときに発生する例外を捕捉しスクリプトが止まらないようにする。
*/
type storageType = 'localStorage' | 'sessionStorage'
class WebStorage {
constructor(private storageType: storageType) {}
private operate<T>(operation: (storage: typeof window[storageType]) => T, fallback: T) {
if (!(this.storageType in window)) {
return fallback
}
try {
return operation(window[this.storageType])
} catch (e) {
console.error(e)
return fallback
}
}
get length() {
return this.operate(storage => storage.length, 0)
}
key(index: number) {
return this.operate(storage => storage.key(index), null)
}
getItem(key: string) {
return this.operate(storage => storage.getItem(key), null)
}
setItem(key: string, value: string) {
return this.operate(storage => storage.setItem(key, value), void 0)
}
removeItem(key: string) {
return this.operate(storage => storage.removeItem(key), void 0)
}
clear() {
return this.operate(storage => storage.clear(), void 0)
}
}
export const localStorage = new WebStorage('localStorage')
export const sessionStorage = new WebStorage('sessionStorage')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment