-
Hello, I would like to have the ability to open a transaction and pass it in the request options. I think having something like this would be useful, even for use in other middlewares.
But now I have to do everything in the handler.
I also tried to do this using expressMiddleware, but it doesn't allow passing options. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 1 reply
-
@BashkaMen |
Beta Was this translation helpful? Give feedback.
-
I need to add an instance of an open transaction (TypeORM EntityManager) to the options.
|
Beta Was this translation helpful? Give feedback.
-
db_transaction в моем примере как middleware заворачивающий весь код в транзакцию
|
Beta Was this translation helpful? Give feedback.
-
One more example for better understanding.
|
Beta Was this translation helpful? Give feedback.
-
Middlewares are not supposed to call endpoints, they are supposed to be executed ahead of endpoint handlers. So, here is the suggested architecture:
const transactionMiddleware = new Middleware({
handler: async () => ({
commit: () => {},
rollback: () => {},
}),
});
const rh = new ResultHandler({
positive: z.any(),
negative: z.any(),
handler: ({ options, error }) => {
if (
error &&
"rollback" in options &&
typeof options.rollback === "function"
)
options.rollback();
},
});
const factory = new EndpointsFactory(rh);
const endpoint = factory.addMiddleware(transactionMiddleware).build({
output: z.object({}),
handler: async ({ options: { commit } }) => {
/** do stuff or throw */
commit();
return {};
},
}); |
Beta Was this translation helpful? Give feedback.
@BashkaMen ,
Middlewares are not supposed to call endpoints, they are supposed to be executed ahead of endpoint handlers.
However, middlewares can equip endpoint handlers with a context that the framework calls
options
.Those
options
can contain such entities as transaction or even callbacks for either to commit or rollback.If the endpoint handler throws, that error goes to
ResultHandler
.You can make a custom one (instead of
defaultResultHandler
), which could also get thoseoptions
and perform the rollback in case of an error.So, here is the suggested architecture:
Middleware
that returns{ commit, rollback }
(callbacks),ResultHandler
that in case oferror
takesrollback
fromopt…