Skip to content

persist

awekrx edited this page May 29, 2026 · 1 revision

persist

Import

import { persist } from '@dev-suite/decorators/persist'

Category

  • property

Use Case

Persist property state to storage adapter automatically.

Replaces

  • Manual localStorage/db sync in setters/getters
  • Custom hydrate/save methods per field

Example 1

Without decorator

class Preferences {
  private _theme = 'light';

  get theme() {
    const saved = localStorage.getItem('theme');
    return saved ?? this._theme;
  }

  set theme(next: string) {
    this._theme = next;
    localStorage.setItem('theme', next);
  }
}

With decorator

import { persist } from '@dev-suite/decorators/persist';

class Preferences {
  @persist({ adapter: localStorageAdapter, key: 'theme' })
  theme = 'light';
}

Why better

  • Centralizes cross-cutting behavior.
  • Method/class/property code stays focused on domain logic.

Example 2

Without decorator

class CartState {
  private _items: CartItem[] = [];

  set items(next: CartItem[]) {
    this._items = next;
    db.save('cart_items', JSON.stringify(next));
  }
}

With decorator

import { persist } from '@dev-suite/decorators/persist';

class CartState {
  @persist({ adapter: dbAdapter, key: 'cart_items', serialize: JSON.stringify, deserialize: JSON.parse })
  items: CartItem[] = [];
}

Why better

  • Second scenario reuses same policy without duplication.
  • Behavior is more consistent and easier to audit.

Clone this wiki locally