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

@elemental-concept/rx-persist

v1.0.1

Published

Persistence operator for RxJS

Downloads

419

Readme

rx-persist

@elemental-concept/rx-persist provides a persistence operator for RxJS subjects. It automatically saves each event emission into selected storage and restores last emission from storage on Subject creation. Additionally, provides storage versioning with persistentAndVersioned operator.

Use-case example

Imagine you're working on a front-end application for an online clothing shop, and you want your users to be able to filter products by size and colour. You might define the following interface to describe such filter:

export interface ProductFilter {
  size: string;
  color: string;
}

export const defaultProductFilter: ProductFilter = {
  size: 'any',
  color: 'any'
};

And then you'd have a subject which will allow different parts of your application to emit new filter values based on user input and to subscribe to such events. You can also chain this filter subject into API call to fetch new data each time your users request changes:

export class ProductsService {
  private apiService = new ApiService();

  private productFilter$ = new BehaviorSubject<ProductFilter>(defaultProductFilter);

  private products$ = this.productFilter$
    .pipe(switchMap(filter => this.apiService.getProducts(filter)));

  get productFilter(): Observable<ProductFilter> {
    return this.productFilter$.asObservable();
  }

  get products(): Observable<Product[]> {
    return this.products$;
  }

  setFilter(filter: ProductFilter) {
    this.productFilter$.next(filter);
  }
}

But what would happen if a user decides to refresh your page in the browser? Filters will be reset to their default state, and most likely this is not something you want to happen. This is where rx-persist comes into play. Simply wrap your subject with persistent operator and each filter change will be stored in window.localStorage:

export class ProductsService {
  // ...

  private productFilter$ = persistent(
    new BehaviorSubject<ProductFilter>(defaultProductFilter),
    'storageKey');

  // ...
}

Installation

Using npm:

$ npm i @elemental-concept/rx-persist

Using Yarn:

$ yarn add @elemental-concept/rx-persist

Example

Check this example for a simple usage example in an Angular application.

API

persistent()

function persistent<T, S extends Subject<T>>(subject: S, key: string | string[], storage: StorageDriver = localStorageDriver): S;
  • subject - specifies a subject to add persistence to.
  • key - key to use to read and write data changes into the storage.
  • storage - optionally specify a storage to use. window.localStorage is used by default.

persistentAndVersioned()

function persistentAndVersioned<T, S extends Subject<T>>(subject: S, key: string | string[], options: VersionedOptions): S;
  • subject - specifies a subject to add persistence to.
  • key - key to use to read and write data changes into the storage.
  • options - set of options for versioning.

VersionedOptions

interface VersionedOptions {
  currentVersion: number;
  versionKey: string | string[];
  migrate: (version: number, value: any) => any;

  storage?: StorageDriver;
}
  • currentVersion - specifies current version application expects.
  • versionKey - storage key to fetch version information.
  • migrate - method to run migrations between versions.
  • storage - same as in persistent().

StorageDriver

type StorageResult<R> = Promise<R> | Observable<R>;

interface StorageDriver {
  set<T, R>(key: string, value: T): void | StorageResult<R>;

  get<T>(key: string): T | null | StorageResult<T | null>;

  remove<R>(key: string): void | StorageResult<R>;
}

Describes a contract to implement custom storage support.

DOMStorageDriver

export class DOMStorageDriver implements StorageDriver {
  constructor(private readonly storage: Storage) {
  }
}

StorageDriver for custom DOM Storage implementations.

sessionStorageDriver

const sessionStorageDriver = new DOMStorageDriver(sessionStorage);

Pre-defined StorageDriver which uses window.sessionStorage as a back-end.

localStorageDriver

const sessionStorageDriver = new DOMStorageDriver(localStorage);

Pre-defined StorageDriver which uses window.localStorage as a back-end.

Versioning

Data structure saved in a persistent Subject might change over life span of your application. To avoid data corruption persistentAndVersioned() operator is introduced to be used instead of persistent(). Versioning starts with 0 and gets incremented by 1 on each data structure change.

When persistentAndVersioned() is called it will load currently saved version from storage from versionKey and will compare this value to currentVersion. It will then call migrate() multiple times passing current version and incrementing it on success. For example, currentVersion is set to 7, but version number obtained from versionKey is 5. In this case migrate() will be called twice: for version 5 and version 6.

migrate() should check current version, apply data transformations and return the result. Result will be immediately saved into storage and current version number will be bumped by 1.

Example

Let's assume the following scenario:

  1. When the app was created, subject contained an object with just one field - name.
  2. After some time new field was added - id.
  3. Finally, data structure was updated to also include user type in a field called type.
  4. Most recent version is thus number 2 and there should be two migrations: from 0 to 1 and from 1 to 2.
persistentAndVersioned<string, Subject<string>>(
  new BehaviorSubject({ id: 1, type: 'GUEST', name: 'Guest' }),
  'user',
  {
    currentVersion: 2,
    versionKey: 'userVersion',
    migrate: (version: number, value: any) => {
      switch (version) {
        case 0:
          value.id = 1;
          break;

        case 1:
          value.type = 'GUEST';
          break;
      }

      return value;
    }
  })
  .subscribe();