Skip to content

Commit

Permalink
馃悰 catch persistence initialisation errors (#264)
Browse files Browse the repository at this point in the history
  • Loading branch information
prazdevs committed Dec 16, 2023
1 parent bf1166f commit 0f21016
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 29 deletions.
70 changes: 43 additions & 27 deletions packages/plugin/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,53 @@ import { normalizeOptions } from './normalize'
import { pick } from './pick'
import {
type PersistedStateFactoryOptions,
type PersistedStateOptions,
type Serializer,
type StorageLike,
} from './types'

interface Persistence {
storage: StorageLike
storage?: StorageLike
serializer: Serializer
key: string
paths: string[] | null
debug: boolean
beforeRestore?: (c: PiniaPluginContext) => void
afterRestore?: (c: PiniaPluginContext) => void
}

function parsePersistence(factoryOptions: PersistedStateFactoryOptions, store: Store) {
return (o: PersistedStateOptions): Persistence | null => {
try {
const {
storage = localStorage,
beforeRestore = undefined,
afterRestore = undefined,
serializer = {
serialize: JSON.stringify,
deserialize: JSON.parse,
},
key = store.$id,
paths = null,
debug = false,
} = o

return {
storage,
beforeRestore,
afterRestore,
serializer,
key: (factoryOptions.key ?? (k => k))(typeof key == 'string' ? key : key(store.$id)),
paths,
debug,
}
}
catch (e) {
if (o.debug)
console.error('[pinia-plugin-persistedstate]', e)
return null
}
}
}

function hydrateStore(
Expand All @@ -31,9 +68,9 @@ function hydrateStore(
if (fromStorage)
store.$patch(serializer?.deserialize(fromStorage))
}
catch (error) {
catch (e) {
if (debug)
console.error(error)
console.error('[pinia-plugin-persistedstate]', e)
}
}

Expand All @@ -45,9 +82,9 @@ function persistState(
const toStore = Array.isArray(paths) ? pick(state, paths) : state
storage!.setItem(key!, serializer!.serialize(toStore as StateTree))
}
catch (error) {
catch (e) {
if (debug)
console.error(error)
console.error('[pinia-plugin-persistedstate]', e)
}
}

Expand Down Expand Up @@ -85,28 +122,7 @@ export function createPersistedState(
Array.isArray(persist)
? persist.map(p => normalizeOptions(p, factoryOptions))
: [normalizeOptions(persist, factoryOptions)]
).map(
({
storage = localStorage,
beforeRestore = null,
afterRestore = null,
serializer = {
serialize: JSON.stringify,
deserialize: JSON.parse,
},
key = store.$id,
paths = null,
debug = false,
}) => ({
storage,
beforeRestore,
afterRestore,
serializer,
key: (factoryOptions.key ?? (k => k))(typeof key == 'string' ? key : key(store.$id)),
paths,
debug,
}),
)
).map(parsePersistence(factoryOptions, store)).filter(Boolean) as Persistence[]

store.$persist = () => {
persistences.forEach((persistence) => {
Expand Down
27 changes: 25 additions & 2 deletions packages/plugin/tests/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,29 @@ describe('default', () => {
})

describe('w/ debug', () => {
it('error logs creation errors (storage permissions)', () => {
//* arrange
const error = new Error('access_denied')
Object.defineProperty(window, 'localStorage', {
get: () => { throw error }
})
const spy = vi
.spyOn(globalThis.console, 'error')
.mockImplementationOnce(() => {})
const useStore = defineStore(key, {
state: () => ({ lorem: '' }),
persist: {
debug: true,
},
})

//* act
useStore()

//* assert
expect(spy).toHaveBeenCalledWith('[pinia-plugin-persistedstate]' ,error)
})

it('error logs hydration errors', () => {
//* arrange
const error = new Error('failed_hydration')
Expand All @@ -451,7 +474,7 @@ describe('default', () => {
useStore()

//* assert
expect(spy).toHaveBeenCalledWith(error)
expect(spy).toHaveBeenCalledWith('[pinia-plugin-persistedstate]' ,error)
})

it('error logs persistence errors', async () => {
Expand Down Expand Up @@ -479,7 +502,7 @@ describe('default', () => {
await nextTick()

//* assert
expect(spy).toHaveBeenCalledWith(error)
expect(spy).toHaveBeenCalledWith('[pinia-plugin-persistedstate]' ,error)
})
})

Expand Down

0 comments on commit 0f21016

Please sign in to comment.