1.0.2 • Published 2 months ago

@spider-baby/ssr-storage v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

@spider-baby/ssr-local-storage

Angular NX TypeScript

A lightweight Angular service that provides a wrapper around the browser's localStorage API with built-in support for Server-Side Rendering (SSR).

Features

  • 🔄 Full localStorage API implementation
  • 🛡️ Type-safe methods for working with objects
  • 🖥️ Server-side rendering compatible
  • ⚠️ Error handling for all storage operations
  • 🪶 Zero dependencies beyond Angular

Installation

npm install @spider-baby/ssr-local-storage

Usage

Setting up the module

import { NgModule } from '@angular/core';
import { SsrLocalStorageModule } from '@spider-baby/ssr-local-storage';

@NgModule({
  imports: [
    SsrLocalStorageModule.forRoot()
  ]
})
export class AppModule { }

Basic operations

import { Component } from '@angular/core';
import { SsrLocalStorageService } from '@spider-baby/ssr-local-storage';

@Component({
  selector: 'app-example',
  template: `<div>{{ storedValue }}</div>`
})
export class ExampleComponent {
  storedValue: string;

  constructor(private storage: SsrLocalStorageService) {
    // Store a value
    this.storage.setItem('greeting', 'Hello, World!');
    
    // Retrieve a value
    this.storedValue = this.storage.getItem('greeting');
    
    // Remove a value
    this.storage.removeItem('oldKey');
    
    // Clear all values
    // this.storage.clear();
  }
}

Working with objects

import { SsrLocalStorageService } from '@spider-baby/ssr-local-storage';

interface User {
  id: number;
  name: string;
  email: string;
}

// Store an object
const user: User = { id: 1, name: 'John Doe', email: 'john@example.com' };
this.storage.setItemObject<User>('currentUser', user);

// Retrieve an object
const storedUser = this.storage.getItemObject<User>('currentUser');

Error handling

try {
  const value = this.storage.getItem('key');
  // Use the value
} catch (error) {
  console.error('Storage operation failed:', error);
  // Handle the error appropriately
}

API Reference

SsrLocalStorageService

Basic Methods

MethodDescriptionParametersReturn
getItem(key: string)Retrieves an item from storagekey: Storage keystring \| null
setItem(key: string, value: string)Stores a string valuekey: Storage keyvalue: String to storevoid
removeItem(key: string)Removes an item from storagekey: Storage keyvoid
clear()Clears all storageNonevoid
key(index: number)Gets the key at the specified indexindex: Numeric positionstring \| null
length()Gets the number of items in storageNonenumber

Object Methods

MethodDescriptionParametersReturn
getItemObject<T>(key: string)Retrieves and parses a JSON objectkey: Storage keyT \| null
setItemObject<T>(key: string, value: T)Stringifies and stores an objectkey: Storage keyvalue: Object to storevoid

SSR Considerations

When running in server-side rendering mode, the service automatically uses an in-memory storage implementation that mimics localStorage behavior. This ensures your application works seamlessly in both client and server environments without modifications.

Examples

Usage with Angular Services

@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor(private storage: SsrLocalStorageService) {}
  
  saveUserPreferences(prefs: UserPreferences): void {
    this.storage.setItemObject('userPreferences', prefs); //<UserPreferences> can be omitted because TypeScript infers the type from the value
  }
  
  getUserPreferences(): UserPreferences | null {
    return this.storage.getItemObject<UserPreferences>('userPreferences');
  }
}

Observable Pattern

@Injectable({
  providedIn: 'root'
})
export class ThemeService {
  private themeSubject = new BehaviorSubject<string>('light');
  public theme$ = this.themeSubject.asObservable();
  
  constructor(private storage: SsrLocalStorageService) {
    const savedTheme = this.storage.getItem('theme') || 'light';
    this.themeSubject.next(savedTheme);
  }
  
  setTheme(theme: string): void {
    this.storage.setItem('theme', theme);
    this.themeSubject.next(theme);
  }
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

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

License

This project is licensed under the MIT License - see the LICENSE file for details.

1.0.2

2 months ago

1.0.1

2 months ago

1.0.0

2 months ago