Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

readonly middleware #11

Open
zuhorer opened this issue Sep 19, 2023 · 0 comments
Open

readonly middleware #11

zuhorer opened this issue Sep 19, 2023 · 0 comments

Comments

@zuhorer
Copy link

zuhorer commented Sep 19, 2023

I just created a readonly middleware

import { IMiddlewareHandler } from "mobx-state-tree";

type ForceWriteWrapper = (fn: () => void) => void;

const createReadonlyMiddleware = (): [IMiddlewareHandler, ForceWriteWrapper] => {
  let writeLock = 0;

  const middleware: IMiddlewareHandler = (call, next) => {
    if (writeLock <= 0) {
      throw new Error(`tried to invoke action '${call.name}' over a readonly node`);
    } else {
      return next(call);
    }
  };

  const forceWrite: ForceWriteWrapper = (fn) => {
    try {
      writeLock++;
      fn();
    } finally {
      writeLock--;
    }
  };

  return [middleware, forceWrite];
};
usage:

const [readonlyMiddleware, forceWrite] = createReadonlyMiddleware();
addMiddleware(node, readonlyMiddleware);

node.setX(12345); // will throw
node.child.setX(12345); // will throw

// if a change wants to be made
forceWrite(() => {
  node.setX(1234);
  node.child.setX(12345);
});

do you think it would be useful to you / should be in mst-middlewares?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant