@edumeron/json-storage

0.0.1 • Public • Published

json-storage

Travis npm package Coveralls standard

A tiny module to manage localStorage.

Installation

yarn add @edumeron/json-storage object-path

npm install @edumeron/json-storage object-path --save

Getting Started

Create your storage:

import createStorage from '@edumeron/json-storage'

const storage = createStorage('my_app_namespace')

Both get and set work with keypath as parameter:

// Set user
storage.set('user', { id: 1, name: 'Peter Parker' })
storage.get('user.name') // Peter Parker

// The avatar object will be created automatically
storage.set('user.avatar.url', 'http://placehold.id/150x150')

storage.get('user')
// { id: 1, name: 'Peter Parker', avatar: { url: ''http://placehold.id/150x150' } }

You can use toJSON to retrieve all data from the storage:

storage.toJSON()
/*
{
  user: {
    id: 1,
    name: 'Peter Parker',
    avatar: {
      url: 'http://placehold.id/150x150'
    }
  }
}
*/

Check out the full API methods below.

API

The API consists of only 4 methods:

get(keypath: string, fallback: any)

Returns the value for the given keypath.

storage.get('user.name') // Peter Parker

// Non-existing property
storage.get('user.age') // undefined

// You can also pass a fallback value
storage.get('user.age', 20) // 20

set(keypath: string, value: any)

Sets a new value for the given keypath.

storage.set('prop', 'some_value') // some_value

// You can pass a function to modify the current value
storage.set('user.permissions',  permissions => {
  return permissions.concat('read')
}) // ['create', 'read']

It always return the value you passed:

console.log(storage.set('prop', 'some_value'))
// => some_value

clear()

Removes all the values from the storage.

storage.clear()

storage.toJSON() // {}

toJSON()

Returns the whole storage as an object.

storage.toJSON();
/*
{
  user: {
    id: 1,
    name: 'Peter Parker',
    avatar: {
      url: 'http://placehold.id/150x150'
    }
  }
}
*/

Tests

npm install

npm test

License

MIT

Package Sidebar

Install

npm i @edumeron/json-storage

Weekly Downloads

0

Version

0.0.1

License

MIT

Unpacked Size

6.94 kB

Total Files

4

Last publish

Collaborators

  • gsantiago