Skip to content

Commit

Permalink
fix: overly zealous localstorage warning (#1430)
Browse files Browse the repository at this point in the history
  • Loading branch information
bmulholland committed Jan 13, 2022
1 parent 71ddfdf commit 1785b0f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
37 changes: 28 additions & 9 deletions src/core/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,11 @@ export class Storage {
return this.removeLocalStorage(key)
}

if (!this.localStorageEnabled() || !this.options.localStorage) {
if (!this.isLocalStorageEnabled()) {
return
}

const _key = this.options.localStorage.prefix + key
const _key = this.getPrefix() + key

try {
localStorage.setItem(_key, encodeValue(value))
Expand All @@ -207,23 +207,24 @@ export class Storage {
}

getLocalStorage(key: string): unknown {
if (!this.localStorageEnabled() || !this.options.localStorage) {
if (!this.isLocalStorageEnabled()) {
return
}

const _key = this.options.localStorage.prefix + key
const _key = this.getPrefix() + key

const value = localStorage.getItem(_key)

return decodeValue(value)
}

removeLocalStorage(key: string): void {
if (!this.localStorageEnabled() || !this.options.localStorage) {
if (!this.isLocalStorageEnabled()) {
return
}

const _key = this.options.localStorage.prefix + key
const _key = this.getPrefix() + key

localStorage.removeItem(_key)
}

Expand Down Expand Up @@ -307,7 +308,24 @@ export class Storage {
this.setCookie(key, undefined, options)
}

localStorageEnabled(): boolean {
getPrefix(): string {
if (!this.options.localStorage) {
throw new Error('Cannot get prefix; localStorage is off')
}
return this.options.localStorage.prefix
}

isLocalStorageEnabled(): boolean {
// Disabled by configuration
if (!this.options.localStorage) {
return false
}

// Local Storage only exists in the browser
if (!process.client) {
return false
}

// There's no great way to check if localStorage is enabled; most solutions
// error out. So have to use this hacky approach :\
// https://stackoverflow.com/questions/16427636/check-if-localstorage-is-available
Expand All @@ -317,10 +335,11 @@ export class Storage {
localStorage.removeItem(test)
return true
} catch (e) {
if (this.options.localStorage) {
if (!this.options.ignoreExceptions) {
// eslint-disable-next-line no-console
console.warn(
"[AUTH] Local storage is enabled in config, but browser doesn't support it"
"[AUTH] Local storage is enabled in config, but browser doesn't" +
' support it'
)
}
return false
Expand Down
2 changes: 1 addition & 1 deletion tsdoc-metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"toolPackages": [
{
"packageName": "@microsoft/api-extractor",
"packageVersion": "7.19.3"
"packageVersion": "7.19.4"
}
]
}

0 comments on commit 1785b0f

Please sign in to comment.