mobx-keystone icon indicating copy to clipboard operation
mobx-keystone copied to clipboard

What is the reason for disallowing promises in middleware (onActionMiddleware, etc.)?

Open AlexShRz opened this issue 9 months ago • 0 comments

👉 Use case:

  1. I want to implement the "command" pattern where I can pass an action through a series of middleware that can modify/cancel it.
  2. Some middleware need to be async - for example I get some data passed to the action, and I need to send it back to the server for analysis, get the response and decide whether the action needs to be cancelled (onStart seems to be perfect for this type of logic).
  3. However, I cannot do that because the middleware does not support promises (or TS types are incomplete, I'm not sure).

❓ What I don't understand: It seems like you have 2 ways of going about this issue - model decorators or creating your Command/CommandInvoker classes. In my humble opinion this makes no sense:

  1. Model actions/flows already support transactions that revert the action in case of an error. You can throw an error inside your middleware to cancel the action.
  2. Keystone middleware already pass a lot of useful context to you - model, action type, etc., you don't have to reimplement the wheel here.
  3. If you decide to go with the decorator approach, TS types will be a pain in the ass as usual, plus you will probably need to pass middleware context to them.
  4. If you decide to go with the Command pattern, you will have to create your own implementation that you need to support (and maybe test too). On top of that:
    1. There are no maintained NPM libraries for CQRS/Commands.
    2. You will have to manually pass context to commands that the "onActionMiddleware" already provides.

✅ What I propose: Please allow us to make onStart/onFinish hooks async inside middleware.

AlexShRz avatar Mar 15 '25 21:03 AlexShRz