UNPKG

@alwatr/local-storage

Version:

A modern, simple, and robust solution for managing versioned JSON objects in the browser's `localStorage`. This package provides a clean, class-based API with a factory function to ensure your application's data persistence is safe, maintainable, and futu

86 lines 2.84 kB
import type { LocalStorageProviderConfig } from './type.js'; /** * A provider class for managing a specific, versioned item in localStorage. * It encapsulates the logic for key generation, serialization, and migration. * * @example * ```typescript * const userSettings = new LocalStorageProvider({ * name: 'user-settings', * version: 1 * }); * * // Write new settings * userSettings.write({ theme: 'dark', notifications: false }); * * // Read the current settings * const currentSettings = userSettings.read(); * console.log(currentSettings); // { theme: 'dark', notifications: false } * ``` */ export declare class LocalStorageProvider<T> { static readonly version: string; private readonly key__; protected readonly logger_: import("@alwatr/logger").AlwatrLogger; protected readonly parse_: (value: string) => T; protected readonly stringify_: (value: T) => string; constructor(config: LocalStorageProviderConfig<T>); /** * Generates the versioned storage key. * @param config - An object containing the name and schemaVersion. * @returns The versioned key string. */ static getKey(config: { name: string; schemaVersion: number; }): string; /** * Manages data migration by removing all previous versions of the item. */ static clearPreviousStorageVersions(config: { name: string; schemaVersion: number; }): void; /** * Checks if a versioned item exists in localStorage for the given configuration. * This static method allows checking for the existence of a specific versioned item * without instantiating the provider. * * @param config - The configuration object containing the name and schemaVersion. * @returns `true` if the item exists in localStorage, otherwise `false`. * * @example * ```typescript * const exists = LocalStorageProvider.has({ name: 'user-form', schemaVersion: 1 }); * ``` */ static has(config: LocalStorageProviderConfig): boolean; /** * Checks if the current versioned item exists in localStorage. * * @returns `true` if the item exists in localStorage, otherwise `false`. * * @example * ```typescript * const provider = new LocalStorageProvider({ name: 'profile', schemaVersion: 2 }); * if (provider.has()) { * // Item exists * } * ``` */ has(): boolean; /** * Reads and parses the value from localStorage. * If the item doesn't exist or is invalid JSON, returns null. */ read(): T | null; /** * Serializes and writes a value to localStorage. */ write(value: T): void; /** * Removes the item from localStorage. */ remove(): void; } //# sourceMappingURL=local-storage.provider.d.ts.map