Skip to content

Interface: IObjectStore<T, CacheDisabled>

Defined in: store/src/types/IObjectStore.ts:6

Represents a generic, reactive, and persistent Map-like data store.

The IStore interface defines the contract for a data structure that combines the standard functionality of a JavaScript Map with advanced features such as RxJS-powered reactivity, optional persistence (e.g., to LocalStorage or a JSON file), and built-in search, sorting, and filtering.

It is designed to be framework-agnostic but provides features that integrate well with reactive systems and modern UI libraries like React.

Template

CacheDisabled

A boolean flag; if true, the store operates without an in-memory cache, reading and writing directly to the underlying storage on every operation.

Extends

  • IStore<keyof T, T[keyof T], CacheDisabled>

Type Parameters

T

T extends object = object

The type of keys used to identify values in the store.

CacheDisabled

CacheDisabled extends boolean = false

The type of values stored in the store.

Properties

cacheDisabled

readonly cacheDisabled: CacheDisabled

Defined in: store/src/types/IStore.ts:83

Disable in-memory cache and only directly read/write from storage (local storage or JSON fle)

Inherited from

IStore.cacheDisabled


clear

readonly clear: () => IStore<keyof T, T[keyof T], CacheDisabled>

Defined in: store/src/types/IStore.ts:248

Clear all items

Returns

IStore<keyof T, T[keyof T], CacheDisabled>

Inherited from

IStore.clear


delay

readonly delay: number

Defined in: store/src/types/IStore.ts:93

Debounce/throttle delay duration in milliseconds for writing to storage when caching is enabled.

Increasing this value can improve performance when dealing with large datasets or frequent updates by reducing the number of write operations.

Default: 300

Inherited from

IStore.delay


delayOptions?

readonly optional delayOptions?: Store_DelayOptions

Defined in: store/src/types/IStore.ts:95

Inherited from

IStore.delayOptions


delete

readonly delete: (key) => IStore<keyof T, T[keyof T], CacheDisabled>

Defined in: store/src/types/IStore.ts:251

Delete one or more items by their respective keys

Parameters

key

keyof T | keyof T[]

Returns

IStore<keyof T, T[keyof T], CacheDisabled>

Inherited from

IStore.delete


filter

readonly filter: <AsArray>(...args) => AsArray extends true ? Map<keyof T, T[keyof T]> : T[keyof T][]

Defined in: store/src/types/IStore.ts:254

Filter items by predicate

Type Parameters

AsArray

AsArray extends boolean = false

Parameters

args

...[FilterPredicate<keyof T, T[keyof T]>, number, AsArray, Map<keyof T, T[keyof T]>]

Returns

AsArray extends true ? Map<keyof T, T[keyof T]> : T[keyof T][]

Inherited from

IStore.filter


find

readonly find: <IncludeKey>(predicateOrOptions) => IncludeKey extends true ? [keyof T, T[keyof T]] : T[keyof T] | undefined

Defined in: store/src/types/IStore.ts:259

Find an item by predicate or search criteria

Type Parameters

IncludeKey

IncludeKey extends boolean = false

Parameters

predicateOrOptions

FilterPredicate<keyof T, T[keyof T]> | FindOptions<keyof T, T[keyof T], IncludeKey>

Returns

IncludeKey extends true ? [keyof T, T[keyof T]] : T[keyof T] | undefined

Inherited from

IStore.find


has

readonly has: (key) => boolean

Defined in: store/src/types/IStore.ts:278

Check if key exists

Parameters

key

keyof T

Returns

boolean

Inherited from

IStore.has


init

readonly init: (initialValue?) => boolean

Defined in: store/src/types/IStore.ts:291

Initializes storage and sets up internal subscriptions.

Manual invocation is not typically necessary, as initialization occurs automatically in one of the following scenarios:

  • During construction, if an initialValue with at least one entry is provided.
  • On the first attempt to read or write data.

Parameters

initialValue?

Map<keyof T, T[keyof T]>

An optional map to initialize the storage with if it's currently empty.

Returns

boolean

true if initialization was successful, or false if the storage was already initialized.

Inherited from

IStore.init


initialized

readonly initialized: boolean

Defined in: store/src/types/IStore.ts:100

Indicates wherether storage has been initialized (init() function invoked).

Inherited from

IStore.initialized


keys

readonly keys: () => keyof T[]

Defined in: store/src/types/IStore.ts:294

Get all keys

Returns

keyof T[]

Inherited from

IStore.keys


map

readonly map: <T>(callback) => T[]

Defined in: store/src/types/IStore.ts:297

Map each item on the data to an Array

Type Parameters

T

T = unknown

Parameters

callback

(value, key, entries, index) => T

Returns

T[]

Inherited from

IStore.map


name?

readonly optional name?: string | null

Defined in: store/src/types/IStore.ts:108

Storage name. Filename (NodeJS) or property name (browser LocalStorage). If empty string or undefined, data will not be saved to storage and will only work in-memory.

Default: null

Inherited from

IStore.name


onChange?

optional onChange?: (this, data) => ValueOrPromise<void | Map<keyof T, T[keyof T]>>

Defined in: store/src/types/IStore.ts:120

A callback function executed whenever a data change occurs within the storage.

This hook allows for reactive side-effects. If the callback throws an error or returns a rejected Promise, the exception is caught gracefully and redirected to the onError callback with the type Store_OnErrorType.onChange.

Note: Execution of this callback is managed by internal subscriptions and will stop firing once unsubscribe is called.

Parameters

this

IStore<keyof T, T[keyof T], CacheDisabled>

data

Map<keyof T, T[keyof T]>

Returns

ValueOrPromise<void | Map<keyof T, T[keyof T]>>

Inherited from

IStore.onChange


onError?

optional onError?: (this, err, type) => ValueOrPromise<void>

Defined in: store/src/types/IStore.ts:136

A global error handler invoked whenever an internal operation fails.

It captures failures in the following areas:

  • Data parsing and serialization (JSON or custom logic).
  • Storage access (e.g., localStorage quota or permission errors).
  • Execution of user-provided callbacks like onChange.

Note: If this handler itself throws an error, the exception is ignored gracefully to prevent application crashes during storage cycles.

Parameters

this

IStore<keyof T, T[keyof T], CacheDisabled>

err

unknown

type

Store_OnErrorType

Returns

ValueOrPromise<void>

Inherited from

IStore.onError


parse?

optional parse?: Store_Parse<TypedMap<T>, IObjectStore<T, CacheDisabled>>

Defined in: store/src/types/IObjectStore.ts:19

A callback to customize the deserialization of data read from storage.

This allows you to transform the raw string from the underlying storage back into a Map<Key, Value>. It serves as the functional inverse of stringify.

Fallback Behavior:

  • If this function is not defined, or returns undefined or a non-map value, the system falls back to internal JSON.parse logic.
  • If the function throws an error, it will use and empty map.

Error Triggers:

Overrides

IStore.parse


read

readonly read: (dataStr?) => Map<keyof T, T[keyof T]>

Defined in: store/src/types/IStore.ts:317

Reads and parses data directly from the persistent storage medium.

This operation is synchronous and does not trigger reactive updates via subject$. It is useful for debugging custom parse logic or manual data retrieval.

If instance.parse function is provided and invokation fails, an empty Map will be returned.

Parameters

dataStr?

string | null

(optional) A raw string to parse. If omitted, the method fetches the current value associated with the instance name from the underlying storage.

Returns

Map<keyof T, T[keyof T]>

Inherited from

IStore.read


readonly search: <MatchExact, AsMap>(...args) => AsMap extends true ? Map<keyof T, T[keyof T]> : T[keyof T][]

Defined in: store/src/types/IStore.ts:345

Search through the stored data (Map<Key, Value>). It supports both a global search (using a string or RegExp) across all properties of an item, and a detailed, field-specific search using a query object.

Type Parameters

MatchExact

MatchExact extends boolean = false

AsMap

AsMap extends boolean = true

Parameters

args

...[SearchOptions<keyof T, T[keyof T], MatchExact, AsMap>]

Returns

AsMap extends true ? Map<keyof T, T[keyof T]> : T[keyof T][]

A Map or an Array containing the matched items, based on the asMap option.

Example

Search for users in a specific city

javascript
import { Store } from '@superutils/store'

const storage = new Store('users', {
  initialValue: new Map([
    [1, { name: 'John Doe', city: 'New York' }],
    [2, { name: 'Jane Doe', city: 'London' }],
    [3, { name: 'Peter Jones', city: 'New York' }],
  ])
})

const nyUsers = storage.search({ query: { city: 'New York' } })
console.log(nyUsers.size) // 2

Inherited from

IStore.search


size

readonly size: number

Defined in: store/src/types/IStore.ts:161

Get the number of items

Inherited from

IStore.size


sort

readonly sort: Store_Sort<keyof T, T[keyof T]>

Defined in: store/src/types/IStore.ts:402

Sort items in the storage.

Param

nameOrComparator

Criteria to sort by. Accepts one of the following:

  • function: A comparator function to sort the data.
  • string: A property name of the value object to sort by.
  • true: Sorts the map by its keys.

Param

options

(optional) Sorting options.

Param

options.save

(optional) Whether to save the sorted data back to storage (localStorage/file).

Returns

The sorted Map.

Inherited from

IStore.sort


spaces?

optional spaces?: number

Defined in: store/src/types/IStore.ts:164

Number of spaces to use when stringifying. Default: undefined

Inherited from

IStore.spaces


storage?

readonly optional storage?: Storage | StorageCompact | null

Defined in: store/src/types/IStore.ts:184

LocalStorage or equivalent storage instance to be used as the underlying storage and to read & write from.

Notes:

  • Ignored when name is falsy (in-memory only mode)
  • For NodeJS or equivalent, an instance of LocalStorage from "node-localstoarge" NPM module can be used.
  • A custom storage that implements StorageCompact interface can also be used both in browser and NodeJS.

Fallback behavior:

  • undefined: will attempt to use globalThis.localStorage, if available
  • null, will defer storage check until initialization on first read/write or when init() invoked manually.
    • If storage is undefined or null will attempt to assign globalTihs.localStorage again
    • If storage is still falsy, will throw an error.

Default:

  • browser: localStorage
  • node: undefined (in-memory mode)

Inherited from

IStore.storage


stringify?

optional stringify?: Store_Stringify<TypedMap<T>, IObjectStore<T, CacheDisabled>>

Defined in: store/src/types/IObjectStore.ts:31

A callback function to customize the serialization of data before it is written to storage.

This allows you to transform the data Map<Key, Value> into a string format suitable for the underlying storage (e.g., JSON). It serves as the functional inverse of parse.

Use this to sanitize data, remove circular references, or optimize the storage size by only persisting necessary fields.

Fallback Behavior:

  • If this function is not defined, or returns undefined or a non-string value, the system falls back to internal JSON.stringify logic.
  • If the function throws an error, it will use and empty string.

Error Triggers:

Param

data

a map of all values stored in this storage

Returns

string or undefined

Example

Sanitize data before saving

javascript
import { Store } from '@superutils/store'

const stringify = data => {
  // Convert Map to an array of entries, removing sensitive fields
  const entries = Array.from(data).map(([id, user]) => {
    const { password, ...publicData } = user
    return [id, publicData]
  })
  return JSON.stringify(entries)
}
const storage = new Store('users', { stringify })

Overrides

IStore.stringify


subject$

readonly subject$: CacheDisabled extends true ? Subject<Map<keyof T, T[keyof T]>> : BehaviorSubject<Map<keyof T, T[keyof T]>>

Defined in: store/src/types/IStore.ts:243

The underlying RxJS subject that serves as the primary reactive interface for observing data modifications.

Its implementation type is determined by the caching strategy:

  • BehaviorSubject: Used when caching is enabled. It maintains the current state and emits it immediately to new subscribers.
  • Subject: Used when caching is disabled. It acts as a pure event pipe, emitting updates only at the moment they occur without retaining an in-memory copy.

Inherited from

IStore.subject$


toArray

readonly toArray: () => [keyof T, T[keyof T]][]

Defined in: store/src/types/IStore.ts:405

Convert list of items (Map) to 2D Array

Returns

[keyof T, T[keyof T]][]

Inherited from

IStore.toArray


toJSON

readonly toJSON: Store_ToJSON<keyof T, T[keyof T]>

Defined in: store/src/types/IStore.ts:408

Convert list of items (Map) to JSON string of 2D Array

Inherited from

IStore.toJSON


toString

readonly toString: (data?) => string

Defined in: store/src/types/IStore.ts:414

Convert list of items (Map) to JSON string of 2D Array

Parameters

data?

Map<keyof T, T[keyof T]>

Returns

string

Inherited from

IStore.toString


type

type: string

Defined in: store/src/types/IObjectStore.ts:13

Default: object

Overrides

IStore.type


unsubscribe

readonly unsubscribe: () => void

Defined in: store/src/types/IStore.ts:424

Unsubscribe from all internal subscriptions.

This will result in:

  • Automatic writing to storage being disabled (manual writes via instance.write() will still work).
  • The onChange callback no longer being triggered.
  • The instance stopping listening to force update cache triggers.

Returns

void

Inherited from

IStore.unsubscribe


validate?

optional validate?: Store_Validate<keyof T, T[keyof T], CacheDisabled, IStore<keyof T, T[keyof T], CacheDisabled>>

Defined in: store/src/types/validate.ts:56

A configuration object containing optional validation hooks for specific store operations.

This structure allows for granular control over write operations, enabling you to define custom logic to intercept and prevent invalid state updates.

Behavior:

  • Invoked immediately before the store's internal state is updated.
  • If validation fails (throw error), the operation is aborted and the error is propagated to the caller.
  • The write validator is invoked during every persistence cycle, serving as a final check after operation-specific hooks (e.g., set or delete).
  • For reference-type values (e.g., Objects, Maps, Arrays), validators can be used to mutate the data (e.g., for normalization) before it is committed.
  • thisArg: all validators are bound to the store instance.

Example

javascript
import { createObjectStore } from '@superutils/store'

const settingsStore = createObjectStore({
  name: 'app-settings',
  initialValue: {
    theme: 'light',
    version: '1.0.0',
  },
  validate: {
    set([key, value]) {
      console.log(this.size) // "this" refers to the store instance
      if (key !== 'theme' || ['light', 'dark', 'system'].includes(value)) return

      // throw error to abort operation
      throw new Error(`Invalid theme: ${value}`)
    },
    delete: ([keys]) => {
      if (!keys.includes('version')) return

      throw new Error('The "version" key is protected and cannot be deleted')
    },
  },
})

settingsStore.set('theme', 'system')
console.log(settingsStore.get('theme')) // 'system'
try {
  settingsStore.set('theme', 'invalid') // throws error
} catch (err) {
  console.error(err.message)
}

Inherited from

IStore.validate


values

readonly values: () => T[keyof T][]

Defined in: store/src/types/IStore.ts:427

Get all values as an array

Returns

T[keyof T][]

Inherited from

IStore.values


write

readonly write: (data?) => boolean

Defined in: store/src/types/IStore.ts:437

Write data to the underlying storage (localStorage or file).

Parameters

data?

Map<keyof T, T[keyof T]>

(optional) Data to write.

  • If provided, it overwrites the storage.
  • If not provided, the current in-memory data is used (if cache is enabled).

Returns

boolean

true if the write was successful, false otherwise.

Inherited from

IStore.write

Methods

get()

get<Key>(key): T[Key] | undefined

Defined in: store/src/types/IObjectStore.ts:15

Get item by key

Type Parameters

Key

Key extends string | number | symbol

Parameters

key

Key

Returns

T[Key] | undefined

Overrides

IStore.get


getAll()

getAll(forceRead?): TypedMap<T>

Defined in: store/src/types/IObjectStore.ts:17

Get all items

Parameters

forceRead?

boolean

Returns

TypedMap<T>

Overrides

IStore.getAll


set()

set<Key, Value>(key, value): IObjectStore<T, CacheDisabled>

Defined in: store/src/types/IObjectStore.ts:21

Set item by key

Type Parameters

Key

Key extends string | number | symbol

Value

Value

Parameters

key

Key

value

Value | ((currentValue?) => Value)

Returns

IObjectStore<T, CacheDisabled>

Example

javascript
import { Store } from '@superutils/store'

const store = new Store<string, number>()
store.set('count', 1)
store.set('count', (prevCount = 0) => prevCount + 1)

Overrides

IStore.set


setAll()

setAll(data?, replace?): IObjectStore<T, CacheDisabled>

Defined in: store/src/types/IObjectStore.ts:26

Set multiple entries at once and/or replace the storage entries

Parameters

data?

T | TypedMap<T>

(optional) Data to add. Default: new Map()

replace?

boolean

(optional) Whether to merge with or replace current data.

  • true: replace all entries with data
  • false: merge with current data (existing entries with matching keys will be overwritten)

Default: false

Returns

IObjectStore<T, CacheDisabled>

Overrides

IStore.setAll


toMap()

toMap(data?): TypedMap<T>

Defined in: store/src/types/IObjectStore.ts:34

Convert data/object to typed map

Parameters

data?

T

Returns

TypedMap<T>


toObject()

toObject<O>(data?): O

Defined in: store/src/types/IObjectStore.ts:36

Convert list of items into an object

Type Parameters

O

O extends object = T

Parameters

data?

Map<keyof T, T[keyof T]> | TypedMap<T>

Returns

O

Overrides

IStore.toObject