import { AsyncStoragePersistor, PersistenceConfig, Persistor, } from './persistor'; import merge from 'deepmerge'; const DEFAULT_SAVE_STATE_DELAY_IN_MS = 1000; const DEFAULT_STORE_NAME = 'default'; export type Notify = (value: V) => void; export type Unsubscribe = () => void; /** * Generic observable store */ interface Observable { subscribe: (callback: Notify) => Unsubscribe; unsubscribe: (callback: Notify) => void; notify: (value: V) => void; } /** * Creates a new observable for a particular type that manages all its subscribers * @returns {Observable} observable object */ const createObservable = (): Observable => { const callbacks: Notify[] = []; const unsubscribe = (callback: Notify) => { callbacks.splice(callbacks.indexOf(callback), 1); }; const subscribe = (callback: Notify) => { callbacks.push(callback); return () => { unsubscribe(callback); }; }; const notify = (value: V) => { for (const callback of [...callbacks]) { callback(value); } }; return { subscribe, unsubscribe, notify }; }; export type Action = (state: T) => T | Promise; // Type for the getState function, it is written as an interface to support overloading interface getStateFunc { (): T; (safe: true): Promise; } /** * Sovran State Store */ export interface Store { /** * Register a callback for changes to the store * @param {Notify} callback - callback to be called when the store changes * @returns {Unsubscribe} - function to unsubscribe from the store */ subscribe: (callback: Notify) => Unsubscribe; /** * Dispatch an action to update the store values * @param {T | Promise} action - action to dispatch * @returns {T} new state */ dispatch: (action: Action) => Promise; /** * Get the current state of the store * @param {boolean} safe - if true it will execute the get async in the queue of the reducers guaranteeing that all the actions are executed before retrieving state * @returns {T | Promise} state, or a promise for the state if executed async in the queue */ getState: getStateFunc; } /** * Creates a simple state store. * @param initialState initial store values * @param storeId store instance id * @returns {Store} object */ export interface StoreConfig { /** * Persistence configuration */ persist?: PersistenceConfig; } /** * Creates a sovran state management store * @param initialState initial state of the store * @param config configuration options * @returns Sovran Store object */ export const createStore = ( initialState: T, config?: StoreConfig ): Store => { let state: T = Array.isArray(initialState) ? ([...initialState] as T) : ({ ...initialState } as T); const queue: { call: Action; finally?: (newState: T) => void }[] = []; const isPersisted = config?.persist !== undefined; let saveTimeout: ReturnType | undefined; const persistor: Persistor = config?.persist?.persistor ?? AsyncStoragePersistor; const storeId: string = isPersisted ? config.persist!.storeId : DEFAULT_STORE_NAME; if (isPersisted) { persistor .get(storeId) .then(async (persistedState) => { if ( persistedState !== undefined && persistedState !== null && typeof persistedState === 'object' ) { const restoredState = await dispatch((oldState) => { return merge(oldState, persistedState); }); config?.persist?.onInitialized?.(restoredState); } else { const stateToSave = getState(); await persistor.set(storeId, stateToSave); config?.persist?.onInitialized?.(stateToSave); } }) .catch((reason) => { console.warn(reason); }); } const updatePersistor = (state: T) => { if (config === undefined) { return; } if (saveTimeout !== undefined) { clearTimeout(saveTimeout); } saveTimeout = setTimeout(() => { void (async () => { try { saveTimeout = undefined; await persistor.set(storeId, state); } catch (error) { console.warn(error); } })(); }, config.persist?.saveDelay ?? DEFAULT_SAVE_STATE_DELAY_IN_MS); }; const observable = createObservable(); const queueObserve = createObservable(); function getState(): T; function getState(safe: true): Promise; function getState(safe?: boolean): T | Promise { if (safe !== true) { return Array.isArray(state) ? ([...state] as T) : { ...state }; } return new Promise((resolve) => { queue.push({ call: (state) => { resolve(state); return state; }, }); queueObserve.notify(queue); }); } const dispatch = async (action: Action): Promise => { return new Promise((resolve) => { queue.push({ call: action, finally: resolve, }); queueObserve.notify(queue); }); }; const processQueue = async (): Promise => { queueObserve.unsubscribe(processQueue); while (queue.length > 0) { const action = queue.shift(); try { if (action !== undefined) { const newState = await action.call(state as T); if (newState !== state) { state = newState; // TODO: Debounce notifications observable.notify(state); if (isPersisted) { updatePersistor(state); } } } } catch { console.log('Promise not handled correctly'); } finally { action?.finally?.(state); } } queueObserve.subscribe(processQueue); return state; }; queueObserve.subscribe(processQueue); const subscribe = (callback: Notify) => { const unsubscribe = observable.subscribe(callback); return () => { unsubscribe(); }; }; return { subscribe, dispatch, getState, }; };