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

session-object

v1.0.4

Published

a TypeScript way to easily manage sessionStorage

Downloads

6

Readme

Manage Session Data with a TypeScript Object

Purpose

The sessionStorage object can be complicated to use for the following reasons:

  • sessionStorage only supports strings. That means you have to use JSON.stringify and JSON.parse to use it for other types.
  • If a key has not been set using sessionStorage, it will return null. That makes is difficult to tell if the key was set to null, or if the key was never set in the first place.
  • There is no TypeScript type safety with sessionStorage

sessionStorage Problem Examples:

function sessionStorageNonString() {
    const dataKey = 'examples::session-storage-problems-non-string::data';

    sessionStorage.setItem(dataKey, 7);
    // Argument of type '7' is not assignable to parameter of type 'string'.
}
function sessionStorageUndefined() {
    const dataKey = 'examples::session-storage-problems-undefined::data';

    sessionStorage.setItem(dataKey, JSON.stringify(undefined));

    let data = JSON.parse(sessionStorage.getItem(dataKey));
    // ERROR SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
}
function sessionStorageNotTypeSafe() {
    const dataKey = 'examples::session-storage-problems-not-type-safe::data';

    sessionStorage.setItem(dataKey, JSON.stringify('Babe Ruth'));

    sessionStorage.setItem(dataKey, JSON.stringify(7));

    // No warnings about type discrepancy
}

SessionObject to the Rescue

The type and key are declared in one line:

const data = new SessionObject<number>('examples::rescue::data');

You can get and save the item easily:

function basicExample() {
    const data = new SessionObject<string>('examples::basic-example::data');

    data.set('Hello World');

    console.log(data.get());
    // Hello World
}

No need to use JSON.stringify or JSON.parse for non-string types:

function counterExample() {
    const data = new SessionObject<number>('examples::counter-example::data');
    data.set(0);

    let count = data.get();

    console.log(count);
    // 0

    count++;

    data.set(count);

    console.log(data.get());
    // 1
}

undefined and null values work like everything else in javascript:

function undefinedExample() {
    const data = new SessionObject<string>('examples::undefined-example::data');

    console.log(data.get());
    // undefined

    console.log(typeof data.get() === 'undefined');
    // true

    data.set('Hello World');

    console.log(data.get());
    // Hello World

    data.delete();

    console.log(typeof data.get() === 'undefined');
    // true
}
function nullExample() {
    let data = new SessionObject<string>('examples::null-example::data');

    data.set(null);

    console.log(data.get());
    // null

    console.log(data.get() === null);
    // true
}

Here is an example of a counter service using SessionObject:

class CounterService {
    // second parameter is default value
    private countData = new SessionObject<number>('counter-service::countData', 0);

    public decrement() {
        this.countData.set(this.countData.get() - 1);
    }

    public getCount() {
        return this.countData.get();
    }

    public increment() {
        this.countData.set(this.countData.get() + 1);
    }

    public reset() {
        this.countData.set(0);
    }
}

Here is an example for storing a user data object:

class User {
    fullname: string;
    email: string;
}
class UserService {
    private userData = new SessionData<User>('examples::user-service::user-data');

    constructor() {
        this.userData.set({
            fullname: 'Babe Ruth',
            email: '[email protected]'
        });
    }

    public updateEmail(email: string) {
        let user = userData.get();

        user.email = email;

        userData.set(user);
    }
}

SessionObject Class Definition

class SessionObject<T extends any>
  • T can be any type
constructor(sessionKey: string, defaultValue?: T);
  • sessionKey
    • must be unique to the session [e.g. sessionStorage.getItem(sessionKey)]
  • defaultValue (optional)
    • this value will be stored only when value for sessionKey has not already been set during current session
get(): T
  • returns value from sessionStorage
set(value: T): void
  • stores the value in sessionStorage
delete(): void
  • removes key from sessionStorage

Best Practices

This is fine for non-object types:

class UserNameService {
    private nameData = new SessionObject<string>('examples::user-name-service::name-data');

    public get name() {
        return this.nameData.get();
    }

    public set name(value: string) {
        this.nameData.set(value);
    }
}

function thisIsFine() {
    const service = new UserNameService();

    service.name = 'Fred';

    console.log(service.name);
    // Fred
}

But can be confusing for object types:

class UserService {
    private userData = new SessionObject<User>('examples::user-service::user-data');

    public get user() {
        return this.user.get();
    }

    public set user(value: User) {
        this.user.set(value);
    }
}

function confuse() {
    const service = new UserService();

    service.user = {
        name: 'Fred Flintstone',
        email: '[email protected]'
    };

    console.log(service.user);
    // {
    //   "name": "Fred Flintstone",
    //   "email": "[email protected]"
    // }

    service.user.email = '[email protected]';

    console.log(service.user);
    // {
    //   "name": "Fred Flintstone",
    //   "email": "[email protected]"
    // }

    // The email field did not change because the object was not replaced with set().
}