storage-settings
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

storage-settings

npm build publish codecov Type Coverage Libraries.io dependency status for latest release Bundlephobia npm

Storage API based settings manager

Getting started

npm i storage-settings

Description

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.

Example

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 })

Readme

Keywords

Package Sidebar

Install

npm i storage-settings

Weekly Downloads

35

Version

0.0.2

License

MIT

Unpacked Size

27.3 kB

Total Files

11

Last publish

Collaborators

  • iyegoroff