@prettygoodtech/namespaced-web-storage
v0.5.0
Published
A thin wrapper to use the Web Storage API with namespaces, easily, and safely.
Downloads
15
Maintainers
Readme
Namespaced Web Storage
A thin wrapper to use the Web Storage API with namespaces, easily, and safely. Built with TypeScript.
Features
- Works with
localStorage
,sessionStorage
, and any Storage-compatible implementation like node-storage-shim for Node.js. - Supports
setItem
,getItem
,deleteItem
,clear
, andkey
methods. - Supports
length
property. - Supports dot and bracket property accessors.
- Supports
Object.keys
,Object.values
, andObject.entries
static methods. - Small footprint with zero dependencies.
- TypeScript declarations.
Installation and Usage
First, install the package:
$ npm install @prettygoodtech/namespaced-web-storage
Now you can use NamespacedStorage
to create a new instance based on your
Storage implementation of choice:
import { NamespacedStorage } from "@prettygoodtech/namespaced-web-storage";
const nsStorage = new NamespacedStorage(window.localStorage, "my-prefix");
// Will store with key my-prefix:preferred-theme
nsStorage.setItem("preferred-theme", "dark");
// Will retrieve item with key my-prefix:last-accessed-on
const lastAccessedOn = nsStorage.getItem("last-accessed-on");
// Dot notation, will use key my-prefix:favorite
nsStorage.favorite = "sport-section";
delete nsStorage.favorite;
// Bracket notation, will use key my-prefix:favorite
nsStorage["favorite"] = "sport-section";
delete nsStorage["favorite"];
Caveats
- This package is still in its infancy and some features are not available yet.
- While you can use third-party
Storage
implementations, they might not follow the spec comprehensively. This means that any quirks they might have will still be present when using this package, and may even lead to unexpected errors. Your mileage may vary.
Contributing
Please read the Contributing Guidelines and abide by the Code of Conduct.
License
Copyright 2023 Matei Bogdan Radu.
Project licensed under the Apache License, Version 2.0 (the "License"). A copy of the License is included with this project at LICENSE. Alternatively, you may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.