Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,12 @@
import { recommendedLibrary } from '@nextcloud/eslint-config'
import { defineConfig } from 'eslint/config'

export default defineConfig([...recommendedLibrary])
export default defineConfig([
...recommendedLibrary,
{
rules: {
// this is quite a lowlevel library without dependencies - so no dependency on the logger
'no-console': 'off',
},
},
])
5 changes: 5 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ export function loadState<T>(app: string, key: string, fallback?: T): T {
window._nc_initial_state.set(selector, parsedValue)
return parsedValue
} catch (error) {
console.error('[@nextcloud/initial-state] Could not parse initial state', { key, app, error })

if (fallback !== undefined) {
return fallback
}
throw new Error(`Could not parse initial state ${key} of ${app}`, { cause: error })
}
}
28 changes: 28 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,31 @@ test('returns cached value with consequent calls', () => {

expect(JSON.parse).toHaveBeenCalledTimes(1)
})

test('throws if state cannot be parsed and no fallback is provided', () => {
const errorLog = vi.spyOn(console, 'error')
errorLog.mockImplementationOnce(() => {})

appendInput('app', 'key', 'value')
const spy = vi.spyOn(JSON, 'parse')
spy.mockImplementationOnce(() => {
throw new Error('mocked parsing exception')
})

expect(() => loadState('app', 'key')).toThrowError('Could not parse initial state key of app')
expect(errorLog).toHaveBeenCalledOnce()
})

test('returns fallback if state cannot be parsed but fallback is provided', () => {
const errorLog = vi.spyOn(console, 'error')
errorLog.mockImplementationOnce(() => {})

appendInput('app', 'key', 'value')
const spy = vi.spyOn(JSON, 'parse')
spy.mockImplementationOnce(() => {
throw new Error('mocked parsing exception')
})

expect(loadState('app', 'key', 'fallback')).toBe('fallback')
expect(errorLog).toHaveBeenCalledOnce()
})