0.0.2 • Published 2 years ago

storage-map v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

storage-map

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

Non-throwing Storage API wrapper

Getting started

npm i storage-map

Description

This is a simple wrapper for a Storage-like object. It converts standard Storage methods getItem, setItem, removeItem and clear into functions that catch all possible exceptions and return a 'success or failure' wrapped value. Converted getItem takes an additional argument - a validating transform.

Read the docs here and check how storage-map infers types at the playground. Also there is a compatible result library - ts-railway.

Example

import { createStorageMap } from 'storage-map'
import { LocalStorage } from 'node-localstorage'
import { isRecord } from 'ts-is-record'

// storage-map 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)

// wrap any Storage-like object
const storageMap = createStorageMap(new LocalStorage('./tmp'))

// value will be stringified
storageMap.setItem('key', { value: 'test' })

// associated value should be validated
const result = storageMap.getItem('key', (value) =>
  isRecord(value) && 'value' in value && typeof value.value === 'string'
    ? success(value)
    : failure('data validation failed' as const)
)

expect(result).toEqual({ tag: 'success', success: { value: 'test' } })