All files / services storage.service.ts

96% Statements 48/50
84.48% Branches 49/58
100% Functions 8/8
95.83% Lines 46/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 1572x 2x 2x 2x                                                       2x 20x 20x 20x 20x               8x 1x     7x 7x   7x 1x   6x   1x 1x                   3x 1x   2x                   12x 1x     11x 11x 9x     2x 1x   1x   2x                     4x 1x     3x 3x 1x   2x 1x   1x   2x                 1x     1x                 7x 1x     6x               1x     1x      
import { LoggerService } from '../logging/logger.service';
import { WINDOW } from '../tokens/window.token';
import { isPlatformBrowser } from '@angular/common';
import { Injectable, inject, PLATFORM_ID } from '@angular/core';
 
/**
 * SSR-safe localStorage wrapper with JSON serialization support.
 *
 * Features:
 * - Automatic JSON serialization/deserialization
 * - SSR-safe (no-op on server)
 * - Type-safe get/set operations
 * - Error handling for quota exceeded and invalid JSON
 *
 * @example
 * ```typescript
 * private readonly storage = inject(StorageService);
 *
 * // Store object
 * this.storage.set('user-preferences', { theme: 'dark', lang: 'ru' });
 *
 * // Retrieve with type
 * const prefs = this.storage.get<UserPreferences>('user-preferences');
 *
 * // Remove
 * this.storage.remove('user-preferences');
 * ```
 */
@Injectable({
    providedIn: 'root',
})
export class StorageService {
    private readonly platformId = inject(PLATFORM_ID);
    private readonly isBrowser = isPlatformBrowser(this.platformId);
    private readonly window = inject(WINDOW);
    private readonly logger = inject(LoggerService).withContext('StorageService');
 
    /**
     * Get value from localStorage
     * @param key - Storage key
     * @returns Parsed value or undefined if not found/invalid
     */
    get<T>(key: string): T | undefined {
        if (!this.isBrowser) {
            return undefined;
        }
 
        try {
            const value = this.window?.localStorage.getItem(key);
            // eslint-disable-next-line no-null/no-null
            if (value === null || value === undefined) {
                return undefined;
            }
            return JSON.parse(value) as T;
        } catch (error) {
            this.logger.warn(`Failed to parse localStorage value for key "${key}"`, error);
            return undefined;
        }
    }
 
    /**
     * Get raw string value from localStorage (no JSON parsing)
     * @param key - Storage key
     * @returns Raw string value or undefined
     */
    getString(key: string): string | undefined {
        if (!this.isBrowser) {
            return undefined;
        }
        return this.window?.localStorage.getItem(key) ?? undefined;
    }
 
    /**
     * Set value in localStorage
     * @param key - Storage key
     * @param value - Value to store (will be JSON stringified)
     * @returns true if successful, false otherwise
     */
    set<T>(key: string, value: T): boolean {
        if (!this.isBrowser) {
            return false;
        }
 
        try {
            this.window?.localStorage.setItem(key, JSON.stringify(value));
            return true;
        } catch (error) {
            // Handle quota exceeded
            if (error instanceof DOMException && error.name === 'QuotaExceededError') {
                this.logger.error(`localStorage quota exceeded for key "${key}"`, error);
            } else {
                this.logger.error(`Failed to set localStorage value for key "${key}"`, error);
            }
            return false;
        }
    }
 
    /**
     * Set raw string value in localStorage (no JSON stringification)
     * @param key - Storage key
     * @param value - String value to store
     * @returns true if successful, false otherwise
     */
    setString(key: string, value: string): boolean {
        if (!this.isBrowser) {
            return false;
        }
 
        try {
            this.window?.localStorage.setItem(key, value);
            return true;
        } catch (error) {
            if (error instanceof DOMException && error.name === 'QuotaExceededError') {
                this.logger.error(`localStorage quota exceeded for key "${key}"`, error);
            } else {
                this.logger.error(`Failed to set localStorage value for key "${key}"`, error);
            }
            return false;
        }
    }
 
    /**
     * Remove value from localStorage
     * @param key - Storage key
     */
    remove(key: string): void {
        Iif (!this.isBrowser) {
            return;
        }
        this.window?.localStorage.removeItem(key);
    }
 
    /**
     * Check if key exists in localStorage
     * @param key - Storage key
     * @returns true if key exists
     */
    has(key: string): boolean {
        if (!this.isBrowser) {
            return false;
        }
        // eslint-disable-next-line no-null/no-null
        return this.window?.localStorage.getItem(key) !== null;
    }
 
    /**
     * Clear all localStorage data
     * Use with caution!
     */
    clear(): void {
        Iif (!this.isBrowser) {
            return;
        }
        this.window?.localStorage.clear();
    }
}