Interface: IStore<Key, Value, CD>
Defined in: store/src/types/IStore.ts:81
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.
Extended by
Type Parameters
Key
Key
The type of keys used to identify values in the store.
Value
Value
The type of values stored in the store.
CD
CD extends boolean = false
Properties
cacheDisabled
readonlycacheDisabled:CD
Defined in: store/src/types/IStore.ts:83
Disable in-memory cache and only directly read/write from storage (local storage or JSON fle)
clear
readonlyclear: () =>IStore<Key,Value,CD>
Defined in: store/src/types/IStore.ts:248
Clear all items
Returns
IStore<Key, Value, CD>
delay
readonlydelay: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
delayOptions?
readonlyoptionaldelayOptions?:Store_DelayOptions
Defined in: store/src/types/IStore.ts:95
delete
readonlydelete: (key) =>IStore<Key,Value,CD>
Defined in: store/src/types/IStore.ts:251
Delete one or more items by their respective keys
Parameters
key
Key | Key[]
Returns
IStore<Key, Value, CD>
filter
readonlyfilter: <AsArray>(...args) =>AsArrayextendstrue?Map<Key,Value> :Value[]
Defined in: store/src/types/IStore.ts:254
Filter items by predicate
Type Parameters
AsArray
AsArray extends boolean = false
Parameters
args
...[FilterPredicate<Key, Value>, number, AsArray, Map<Key, Value>]
Returns
AsArray extends true ? Map<Key, Value> : Value[]
find
readonlyfind: <IncludeKey>(predicateOrOptions) =>IncludeKeyextendstrue? [Key,Value] :Value|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<Key, Value> | FindOptions<Key, Value, IncludeKey>
Returns
IncludeKey extends true ? [Key, Value] : Value | undefined
get
readonlyget: (key) =>Value|undefined
Defined in: store/src/types/IStore.ts:266
Get item by key
Parameters
key
Key
Returns
Value | undefined
getAll
readonlygetAll: (forceUpdate?) =>Map<Key,Value>
Defined in: store/src/types/IStore.ts:275
Get all items
Parameters
forceUpdate?
boolean
(optional) if true and cache is enabled, reads & updates data directly from storage
Default: false
Returns
Map<Key, Value>
has
readonlyhas: (key) =>boolean
Defined in: store/src/types/IStore.ts:278
Check if key exists
Parameters
key
Key
Returns
boolean
init
readonlyinit: (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
initialValuewith at least one entry is provided. - On the first attempt to read or write data.
Parameters
initialValue?
Map<Key, Value>
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.
initialized
readonlyinitialized:boolean
Defined in: store/src/types/IStore.ts:100
Indicates wherether storage has been initialized (init() function invoked).
keys
readonlykeys: () =>Key[]
Defined in: store/src/types/IStore.ts:294
Get all keys
Returns
Key[]
map
readonlymap: <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[]
name?
readonlyoptionalname?: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
onChange?
optionalonChange?: (this,data) =>ValueOrPromise<void|Map<Key,Value>>
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<Key, Value, CD>
data
Map<Key, Value>
Returns
ValueOrPromise<void | Map<Key, Value>>
onError?
optionalonError?: (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.,
localStoragequota 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<Key, Value, CD>
err
unknown
type
Returns
ValueOrPromise<void>
parse?
optionalparse?:Store_Parse<Map<Key,Value>,IStore<Key,Value,CD>>
Defined in: store/src/types/IStore.ts:158
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
undefinedor a non-map value, the system falls back to internalJSON.parselogic. - If the function throws an error, it will use and empty map.
Error Triggers:
- If this custom
parsefunction fails: onError is triggered with Store_OnErrorType.parse. - If the default
JSON.parsefallback fails: onError is triggered with Store_OnErrorType.parse_json.
read
readonlyread: (dataStr?) =>Map<Key,Value>
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<Key, Value>
search
readonlysearch: <MatchExact,AsMap>(...args) =>AsMapextendstrue?Map<Key,Value> :Value[]
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<Key, Value, MatchExact, AsMap>]
Returns
AsMap extends true ? Map<Key, Value> : Value[]
A Map or an Array containing the matched items, based on the asMap option.
Example
Search for users in a specific city
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) // 2set
readonlyset: (key,value) =>IStore<Key,Value,CD>
Defined in: store/src/types/IStore.ts:370
Set item by key
Parameters
key
Key
value
Value | ((currentValue?) => Value)
Returns
IStore<Key, Value, CD>
Example
import { Store } from '@superutils/store'
const store = new Store<string, number>()
store.set('count', 1)
store.set('count', (prevCount = 0) => prevCount + 1)setAll
readonlysetAll: (data?,replace?) =>IStore<Key,Value,CD>
Defined in: store/src/types/IStore.ts:385
Set multiple entries at once and/or replace the storage entries
Parameters
data?
Map<Key, Value>
(optional) Data to add. Default: new Map()
replace?
boolean
(optional) Whether to merge with or replace current data.
true: replace all entries withdatafalse: merge with current data (existing entries with matching keys will be overwritten)
Default: false
Returns
IStore<Key, Value, CD>
size
readonlysize:number
Defined in: store/src/types/IStore.ts:161
Get the number of items
sort
readonlysort:Store_Sort<Key,Value>
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.
spaces?
optionalspaces?:number
Defined in: store/src/types/IStore.ts:164
Number of spaces to use when stringifying. Default: undefined
storage?
readonlyoptionalstorage?: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
nameis falsy (in-memory only mode) - For NodeJS or equivalent, an instance of
LocalStoragefrom "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 useglobalThis.localStorage, if availablenull, will defer storage check until initialization on first read/write or wheninit()invoked manually.- If storage is
undefinedornullwill attempt to assignglobalTihs.localStorageagain - If storage is still falsy, will throw an error.
- If storage is
Default:
- browser:
localStorage - node:
undefined(in-memory mode)
stringify?
optionalstringify?:Store_Stringify<Map<Key,Value>,IStore<Key,Value,CD>>
Defined in: store/src/types/IStore.ts:225
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
undefinedor a non-string value, the system falls back to internalJSON.stringifylogic. - If the function throws an error, it will use and empty string.
Error Triggers:
- If this custom
stringifyfunction fails: onError is triggered with Store_OnErrorType.stringify. - If the default
JSON.stringifyfallback fails: onError is triggered with Store_OnErrorType.stringify_json.
Param
data
a map of all values stored in this storage
Returns
string or undefined
Example
Sanitize data before saving
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 })subject$
readonlysubject$:CDextendstrue?Subject<Map<Key,Value>> :BehaviorSubject<Map<Key,Value>>
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.
toArray
readonlytoArray: () => [Key,Value][]
Defined in: store/src/types/IStore.ts:405
Convert list of items (Map) to 2D Array
Returns
[Key, Value][]
toJSON
readonlytoJSON:Store_ToJSON<Key,Value>
Defined in: store/src/types/IStore.ts:408
Convert list of items (Map) to JSON string of 2D Array
toObject
readonlytoObject: <T>(data?) =>T
Defined in: store/src/types/IStore.ts:411
Convert list of items into an object
Type Parameters
T
T extends object = object
Parameters
data?
Map<Key, Value>
Returns
T
toString
readonlytoString: (data?) =>string
Defined in: store/src/types/IStore.ts:414
Convert list of items (Map) to JSON string of 2D Array
Parameters
data?
Map<Key, Value>
Returns
string
type
type:
string
Defined in: store/src/types/IStore.ts:232
Indicates type of data parsed as
Default: 'map'
unsubscribe
readonlyunsubscribe: () =>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
onChangecallback no longer being triggered. - The instance stopping listening to force update cache triggers.
Returns
void
validate?
optionalvalidate?:Store_Validate<Key,Value,CD,IStore<Key,Value,CD>>
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
writevalidator is invoked during every persistence cycle, serving as a final check after operation-specific hooks (e.g.,setordelete). - 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
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)
}values
readonlyvalues: () =>Value[]
Defined in: store/src/types/IStore.ts:427
Get all values as an array
Returns
Value[]
write
readonlywrite: (data?) =>boolean
Defined in: store/src/types/IStore.ts:437
Write data to the underlying storage (localStorage or file).
Parameters
data?
Map<Key, Value>
(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.