mobx-keystone-mindreframer
Version:
A MobX powered state management solution based on data trees with first class support for Typescript, snapshots, patches and much more
36 lines (35 loc) • 1.3 kB
TypeScript
import type { ActionMiddlewareDisposer } from "../action/middleware";
/**
* Return type for readonly middleware.
*/
export interface ReadonlyMiddlewareReturn {
allowWrite<FN extends () => any>(fn: FN): ReturnType<FN>;
dispose: ActionMiddlewareDisposer;
}
/**
* Attaches an action middleware that will throw when any action is started
* over the node or any of the child nodes, thus effectively making the subtree
* readonly.
*
* It will return an object with a `dispose` function to remove the middleware and a `allowWrite` function
* that will allow actions to be started inside the provided code block.
*
* Example:
* ```ts
* // given a model instance named todo
* const { dispose, allowWrite } = readonlyMiddleware(todo)
*
* // this will throw
* todo.setDone(false)
* await todo.setDoneAsync(false)
*
* // this will work
* allowWrite(() => todo.setDone(false))
* // note: for async always use one action invocation per allowWrite!
* await allowWrite(() => todo.setDoneAsync(false))
* ```
*
* @param subtreeRoot Subtree root target object.
* @returns An object with the middleware disposer (`dispose`) and a `allowWrite` function.
*/
export declare function readonlyMiddleware(subtreeRoot: object): ReadonlyMiddlewareReturn;