JavaScript: gestire il web storage con un oggetto wrapper

La gestione del web storage in JavaScript può essere semplificata creando un oggetto wrapper.

JavaScript di Gabriele Romanato

La gestione del web storage in JavaScript può essere semplificata creando un oggetto wrapper.

La soluzione è la seguente:


const Storage = {
	
	type: sessionStorage, // Oppure localStorage
	
    set( item, value ) {
        this.type.setItem( item, value );
    },
    
    get( item ) {
        return this.type.getItem( item );
    },
    
    count() {
        return this.type.length;
    },
    
    remove( item ) {
        this.type.removeItem( item );
    },
    
    empty() {
       this.type.clear();
    },
    
    saveObject( item, obj ) {
        if ( typeof obj === 'object' ) {
            this.set( item, JSON.stringify( obj ) );
        } else {
            throw new Error('Could not convert to JSON string.');
        }
    },
    
    getObject( item ) {
        return JSON.parse( this.get( item ) );
    }
};