Storage API based settings manager
npm i storage-settings
This is simple settings manager that wraps Storage
-like object, emits 'onChange' events, catches all possible exceptions and returns a 'success or failure' wrapped values. The first parameter is an object that maps setting name to validating transform and default value, the second one - Storage
-like object.
Read the docs here and check how storage-settings
infers types at the playground. Also there is a compatible result library - ts-railway.
import { createStorageSettings } from 'storage-settings'
// storage-settings compatible result creators
const success = <T>(value: T) => ({ tag: 'success', success: value } as const)
const failure = <T>(error: T) => ({ tag: 'failure', failure: error } as const)
// define a settings shape and wrap any Storage-like object
const settings = createStorageSettings(
{
foo: {
map: (x) => (typeof x === 'string' ? success(x) : failure('foo is not a string' as const)),
default: ''
},
bar: {
map: (x) => (typeof x === 'number' ? success(x) : failure('bar is not a number' as const)),
default: 0
}
},
localStorage
)
expect(settings.setBar(123)).toEqual({ tag: 'success', success: undefined })
// OK - bar is a number
expect(settings.getBar()).toEqual({ tag: 'success', success: 123 })
// underlying storage is corrupted
localStorage.setItem('bar', JSON.stringify('a string'))
// validation fails - bar is not a number
expect(settings.getBar()).toEqual({ tag: 'failure', failure: 'bar is not a number' })
// reset settings to default values
settings.reset()
// OK - bar is a number
expect(settings.getBar()).toEqual({ tag: 'success', success: 0 })
Generated using TypeDoc