Skip to main content

This package is Powerful, Full Typesafe utility for storage (such as localstorage, cookie, ext.) with safe JSON serialization and more

This package works with Bun, Node.js, Deno, Browsers
JSR Score
100%
Published
a week ago (1.0.2)

@pipisasa/storage - Typesafe Storage with event listeners.

Such as LocalStorage, SessionStorage, Cookie ext.

Example

// example.ts
import { EventHandler, Storage } from "./mod";
import { LocalStorageProvider } from "./src/providers/localStorage";
import { defaultJSONSerializer } from "./src/serializers/defaultJSONSerializer";

type Product = {
  id: number;
  name: string;
};

type MyStorage = {
  accessToken: string;
  refreshToken: string;
  products: Product[];
};

const storage = new Storage<MyStorage>({
  prefix: "some-prefix:",
  provider: new LocalStorageProvider(),
  jsonSerializer: defaultJSONSerializer,
});

// const storageWithSuperJson = new Storage<MyStorage>({
//   prefix: "some-prefix:",
//   provider: new LocalStorageProvider(),
//   jsonSerializer: {
//     stringify(value) {
//       return superjson.stringify(value);
//     },
//     parse(value) {
//       return superjson.parse(value);
//     }
//   }
// });

const a = storage.get("products"); // a: Product[]

storage.set("products", [{ id: 123, name: "adsfasdf" }]);

const handleProductsSet: EventHandler<MyStorage, "products", "set"> = (e) => {
  console.log(e.type, e.key, e.value);
};

storage.addEventListener("products:set", handleProductsSet);

storage.removeEventListener("products:set", handleProductsSet);

const unsubscribe = storage.addEventListener("products:*", (e) => {
  console.log(e.type, e.key, e.value);
});

unsubscribe();

storage.clear();

Add Package

deno add @pipisasa/storage

Import symbol

import * as mod from "@pipisasa/storage";

Add Package

npx jsr add @pipisasa/storage

Import symbol

import * as mod from "@pipisasa/storage";

Add Package

yarn dlx jsr add @pipisasa/storage

Import symbol

import * as mod from "@pipisasa/storage";

Add Package

pnpm dlx jsr add @pipisasa/storage

Import symbol

import * as mod from "@pipisasa/storage";

Add Package

bunx jsr add @pipisasa/storage

Import symbol

import * as mod from "@pipisasa/storage";