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 #1064

Closed
xaviergonz opened this issue Oct 27, 2018 · 3 comments
Closed

readonly middleware #1064

xaviergonz opened this issue Oct 27, 2018 · 3 comments
Labels
enhancement Possible enhancement

Comments

@xaviergonz
Copy link
Contributor

xaviergonz commented Oct 27, 2018

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?

@xaviergonz xaviergonz added the enhancement Possible enhancement label Oct 27, 2018
@xaviergonz
Copy link
Contributor Author

@mweststrate @k-g-a any thoughts?

@zuhorer
Copy link

zuhorer commented Sep 19, 2023

issue moved to : coolsoftwaretyler/mst-middlewares#11

@coolsoftwaretyler
Copy link
Collaborator

Hey @xaviergonz - we have split mst-middlewares out into its own repo. I'm going to close this issue and track it over in coolsoftwaretyler/mst-middlewares#11.

Thanks!

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

No branches or pull requests

3 participants