safe-web-storage is a safe way for you to work with web storage using a purer functional style.
safe-web-storage
is available from npm
.
$ npm install safe-web-storage -S
The idea is to use data structure called Result from folktale that models the result of operations that may fail. You don't need to check if the value exists, because it will only come in .map
when you have it.
- Fallback (in-memory implementation if default browser implementations aren't available).
- Prefix (Set a default prefix)
JSON.parse
by default when you get itemJSON.stringify
by default when you set item
const safestorage = require('safe-web-storage')
const storage = safestorage({ prefix: 'safe' })
storage
.local
.setItem('name', 'victor igor') //saved on 'safe-name' on localStorage
.map(_ => console.log('saved: ', _)) //{name: "name", value: "victor igor"}
storage
.local
.getItem('name')
.map(console.log) //victor igor
storage
.local
.key(0)
.map(console.log) //safe-name
storage
.local
.removeItem('name')
.map(() => console.log('removed'))
storage
.local
.clear() /clean localStorage
You can use to session or local storage.
const safestorage = require('safe-web-storage')
const storage = safestorage({ prefix: 'safe' })
const local = storage.local
const session = storage.session
local
.setItem('name', 'victor igor') //saved on 'safe-name' on localStorage
.map(_ => console.log('saved: ', _)) //{name: "name", value: "victor igor"}
session
.setItem('name', 'victor igor') //saved on 'safe-name' on localStorage
.map(_ => console.log('saved: ', _)) //{name: "name", value: "victor igor"}
const safestorage = require('safe-web-storage')
const storage = safestorage()
const local = storage.local
const nameFormatted = local.getItem('name').getOrElse('Victor') //victor
const safestorage = require('safe-web-storage')
const storage = safestorage()
const local = storage.local
local
.setItem('age', 20)
const maxAge = local.getItem('age')
.map(age => age + 10)
.getOrElse(10) //30
const safestorage = require('safe-web-storage')
const storage = safestorage({ prefix: 'hj' })
const local = storage.local
local
.setAllItems({ age: 20, name: 'victor', description: 'Lorem' })
//Save on localStorage:
//hj-age
//hj-name
//hj-description
const safestorage = require('safe-web-storage')
const storage = safestorage({ prefix: 'hj' })
const local = storage.local
local
.getAllItems(['age', 'name','description'])
.map(console.log) //{ age: 20, name: 'victor', description: 'Lorem' }
The code is available under the MIT License.