@faizaanceg/pandora

2.0.0 • Public • Published

@faizaanceg/pandora

A tiny wrapper over Storage to improve DX.

Motivation

Ever felt that localStorage is good but it could be better? This library bridges that gap and gives you a pleasant experience when working with localStorage.

Benefits

  • Smooth use with objects.
  • Expirable values (configurable with ttl option).

Installation

npm install @faizaanceg/pandora --save

or

yarn add @faizaanceg/pandora

Usage

import KV from "@faizaanceg/pandora";
import { KeyValueStore } from "@faizaanceg/pandora/kv";

// Can also work with any object that implements `Storage`.

const sessionKV = new KeyValueStore(sessionStorage);
sessionKV.set("ui-preference", "dark");
let uiPreference = sessionKV.get("ui-preference") // "dark"

// Set an item

/*
  localStorage.setItem("username", "pandora");
*/
KV.set("username", "pandora");

// Get an item

/*
  let value = localStorage.getItem("key");
*/
let value = KV.get("key");

// Managing default values

/*
  let defaultValue = 1;
  let count = localStorage.getItem("count") || defaultValue;
*/
let count = KV.get("count", 1);

// Dealing with objects

/*
  let object = { someKey: "value" };
  localStorage.setItem("object", JSON.stringify(object));

  let fromStorage = JSON.parse(localStorage.getItem("object"));
  console.log(fromStorage.someKey); // value
*/
let object = { someKey: "value" };
KV.set("object", object);

let fromStorage = KV.get("object"); // JSON.parse happens internally
console.log(fromStorage.someKey); // value;

// Clear items

/*
  localStorage.clear()
*/
KV.clear();

// Persist values

/*
  let value  = localStorage.getItem("key");
  localStorage.clear();
  localStorage.setItem("key", value);
*/
KV.set("key", value, { shouldPersist: true });
KV.clear();
KV.get("key") === value; // true

For more examples, you can check out the test.mjs file.

Tests

npm install
npm test

Dependencies

None

License

MIT

Package Sidebar

Install

npm i @faizaanceg/pandora

Weekly Downloads

554

Version

2.0.0

License

MIT

Unpacked Size

8.02 kB

Total Files

7

Last publish

Collaborators

  • faizaanceg