npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-storage-safe

v1.0.1

Published

A TypeScript wrapper for localStorage with prefixing and custom serialization support

Downloads

136

Readme

ts-storage-safe

A type-safe, feature-rich wrapper for localStorage with support for prefixing, custom serialization, and namespacing.

Features

  • 🔒 Type-safe: Full TypeScript support with generic types
  • 🔑 Namespacing: Prefix your storage keys to avoid conflicts
  • 🔄 Custom Serialization: Use your own serialization methods
  • 🚀 Simple API: Intuitive methods for all localStorage operations
  • Error Handling: Proper error handling with descriptive messages
  • 🧪 Well Tested: Comprehensive test coverage

Installation

npm install ts-storage-safe

Basic Usage

import { storage } from 'ts-storage-safe';

// Store data with type safety
interface User {
  name: string;
  age: number;
}

storage.set<User>('user', { name: 'John', age: 30 });

// Retrieve data with type inference
const user = storage.get<User>('user');
console.log(user?.name); // John

// Check if key exists
if (storage.has('user')) {
  // Key exists
}

// Remove specific item
storage.remove('user');

// Clear all items
storage.clear();

Namespaced Storage

Create isolated storage instances with prefixes to avoid key conflicts:

import { createStorage } from 'ts-storage-safe';

// Create namespaced storage instances
const userStorage = createStorage({ prefix: 'user' });
const appStorage = createStorage({ prefix: 'app' });

// Each storage instance has its own namespace
userStorage.set('theme', 'dark');     // Stored as 'user:theme'
appStorage.set('theme', 'light');     // Stored as 'app:theme'

// Clear only items in a specific namespace
userStorage.clear();  // Only clears items prefixed with 'user:'

Custom Serialization

Implement custom serialization for special use cases:

import { createStorage } from 'ts-storage-safe';

// Example: Base64 serialization
const secureStorage = createStorage({
  serializer: {
    stringify: <T>(value: T): string => {
      const jsonString = JSON.stringify(value);
      return Buffer.from(jsonString).toString('base64');
    },
    parse: <T>(value: string): T => {
      const jsonString = Buffer.from(value, 'base64').toString();
      return JSON.parse(jsonString);
    }
  }
});

// Data will be stored in base64 format
secureStorage.set('secret', { apiKey: '12345' });

Default Values

Provide fallback values when retrieving data:

interface Settings {
  theme: 'light' | 'dark';
  fontSize: number;
}

const defaultSettings: Settings = {
  theme: 'light',
  fontSize: 14
};

// Returns defaultSettings if 'settings' key doesn't exist
const settings = storage.get<Settings>('settings', defaultSettings);

Error Handling

The library provides descriptive error messages:

try {
  storage.set('data', new WeakMap()); // Non-serializable data
} catch (error) {
  console.error('Storage error:', error.message);
  // Error: Failed to set item: Invalid data structure
}

API Reference

Classes

LocalStorage

Main storage class with type-safe methods.

class LocalStorage {
  constructor(options?: StorageOptions);
  
  set<T>(key: string, value: T): void;
  get<T>(key: string, defaultValue?: T): T | undefined;
  remove(key: string): void;
  clear(clearAll?: boolean): void;
  has(key: string): boolean;
}

Interfaces

StorageOptions

Configuration options for creating storage instances.

interface StorageOptions {
  prefix?: string;
  serializer?: {
    stringify: <T>(value: T) => string;
    parse: <T>(value: string) => T;
  };
}

Exports

  • storage: Default storage instance
  • createStorage: Factory function for creating new storage instances
  • LocalStorage: Storage class for extending or type references

Development

# Install dependencies
npm install

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Build package
npm run build

# Lint code
npm run lint

Type Safety Examples

// Type inference works automatically
storage.set('number', 42);
const num = storage.get<number>('number');  // type: number | undefined

// Complex types
interface UserPreferences {
  theme: 'light' | 'dark';
  notifications: boolean;
  fontSize: number;
}

storage.set<UserPreferences>('prefs', {
  theme: 'dark',
  notifications: true,
  fontSize: 16
});

// TypeScript will enforce correct types
const prefs = storage.get<UserPreferences>('prefs');
if (prefs?.theme === 'dark') {
  // Type-safe access to properties
}

License

MIT

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Issues

Please file any issues, bugs, or feature requests in the issue tracker.