Skip to content

hook: afterCommit? #2805

Closed
Closed

Description

@nextor2k

Using the hooks to emit real-time events, how to ensure that this transaction was not rollbacked? Assuming that the trigger is activated even if the transaction is not completed.

My current strategy is creating a timeout in the hook that will check within period of time if that event was created (in the case of afterCreate) going in the database and making sure that the record exists.

I wonder if there is no possibility to do this without go to the database everytime, if somehow I could have the object of the transaction and it keep track of her situation?

Activity

  1. cusspvz commented on Dec 31, 2014

    @cusspvz

    Could you please specify an example of your afterCreate hook?

    I think you could missed a return of a Promise or called callback without breaking function flow.

  2. mickhansen commented on Dec 31, 2014

    @mickhansen
    Contributor

    Since the transaction is run outside of the create (and thus outside of the hooks) you can't check the transaction status inside the hooks.

    It's however an interesting problem, since using hooks for frontend synchronization is really ideal.

  3. nextor2k commented on Jan 5, 2015

    @nextor2k
    Author

    which way i could check the transaction status outside of hooks?

  4. mickhansen commented on Jan 5, 2015

    @mickhansen
    Contributor

    @nestorneto well like i wrote, i'm not sure you can right now.

  5. mickhansen commented on Jan 5, 2015

    @mickhansen
    Contributor

    Ah my bad - Well .transaction() returns a promise so you just use .then() or .catch()

  6. cusspvz commented on Jan 6, 2015

    @cusspvz

    @mickhansen I'm not sure, but i think that @nestorneto may be experiencing some flow control fault on hooks or bad app structure (since post-transaction code should be where the transaction is being started).

    Inspite that, what do you think about transaction hooks? I can't image a usage case example, unless we give namespaces into transactions, but i don't see the point.

  7. mickhansen commented on Jan 7, 2015

    @mickhansen
    Contributor

    @cusspvz we'd have to find a usecase.

    But perhaps we could expose a promise property from the transaction object so you could do something like:

    Notification.afterCreate(function (notification, options) {
      options.transaction.promise.then(function () {
       // send email
      });
    });

    Obviously you could not return the transaction promise to the hook since it would never finish, but it could work for side effect hooks that don't touch sequelize.

  8. nextor2k commented on Jan 7, 2015

    @nextor2k
    Author

    If every time I create a task I have to emit a realtime event, it makes no sense to worry about it in each code that performs this action. This is why I am trying to emit by hooks. In cases that do not have transaction, works perfectly.

    @mickhansen this would work fine for what I need.

  9. mickhansen commented on Jan 7, 2015

    @mickhansen
    Contributor

    @nestorneto yeah i understand your problem completely, and it's one i'd like to adress, just not sure how to do it perfectly.

  10. cusspvz commented on Jan 7, 2015

    @cusspvz

    @nestorneto
    If every time I create a task I have to emit a realtime event, it makes no sense to worry about it in each code that performs this action.

    Does the event triggers some sort of data loading mechanism?

  11. neekey commented on Mar 24, 2015

    @neekey

    +1 for this, I'm implementing a web-hook service, and one of my hook types is "after-create", so what I did is querying the new item just created associated with related datas in the "afterCreate" hook, and the result end up with the id I provided can't be found at that time.

    models.schema.hook( 'afterCreate', function( schema, options, next ){
            hookHandle( "SCHEMA_CREATE", schema.id );
    });
    
    function hookHandle( type, schemaId ){
    
        Promise.join(
        SchemaProxy.findOneWIthAll( schemaId ),
        SchemaProxy.getHooks( schemaId ), function( schema, hooks ){
            // handle the hooks and datas
        }
    }
  12. mickhansen commented on Mar 24, 2015

    @mickhansen
    Contributor

    @neekey It would be findable if you used the transaction in the hook aswell - But obviously that won't solve the rollback issue.

  13. cusspvz commented on Mar 24, 2015

    @cusspvz

    @mickhansen is there any sense in rerun hooks triggered inside a transaction when it is commited? Or even run transaction hooks, don't know.

    Example:

    • transaction
    • instance build
    • instance save
    • instance update
    • instance save
    • transaction commit

    would trigger hooks:

    • sequelize.afterTransaction
    • model.afterBuildOnTransaction
    • model.afterCreateOnTransaction
    • model.afterUpdateOnTransaction
    • sequelize.afterTransactionCommit
    • model.afterBuild
    • model.afterCreate
    • model.afterUpdate
  14. mickhansen commented on Mar 24, 2015

    @mickhansen
    Contributor

    @cusspvz That would be a lot to maintain, the transaction might span 50 calls that each have to track when the transaction is committed to fire and extra hook.

    How do other ORMs deal with this issue?

  15. mdarveau commented on Mar 30, 2015

    @mdarveau
    Contributor

    @cusspvz @nestorneto You could use the instance hook to queue pending (uncommitted) changes into some singleton "real-time event manager" that would map the current transaction to a list of created/updated/deleted records. You can then systematically add a post-transaction hook that would call the real-time event manager and make it dequeue whatever it stored.

    This assumes you can get a reference to the current transaction in the hook, but it should be the case if you use CLS and if not, the transaction might be in the options passed to the hook.

    It's a little error prone to have to put a post-transaction handler so maybe there could be some kind of global post-transaction hook implemented in sequelize?

    This design could be built-in sequelize but it could have negative performance/memory impact. I believe it could also be done as a plugin that would add generic hooks on your model and provide the singleton manager that track changes.

  16. 26 remaining items

  17. stale commented on Jul 17, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  18. EToreo commented on Jul 19, 2017

    @EToreo
    Contributor

    I think this is still needed.

  19. iamjochem commented on Aug 16, 2017

    @iamjochem
    Contributor

    I offer an alternative work-around that you can implement in your own code (check the 2nd comment in #8115) - the difference between my work-around and that offered by @drunkhacker is that mine applies at the point a "std" sequelize hook is defined rather than in the place where a transaction is used (this might be useful for users who already have a pile of hook functions defined)

  20. zekenie commented on Sep 16, 2017

    @zekenie

    Having a transaction commit hook would be extremely helpful for me. Like everyone above has mentioned when you need to do something like fire off a websocket event after an instance has been created, but want to wait to make sure the instance isn't rolled back, there's no great way to do that. That means if there's something else on the transaction that causes a rollback, my frontend might be notified of something that never actually committed.

  21. bradley commented on Jan 23, 2020

    @bradley

    Not sure why I had such a hard time finding this but maybe it will help someone else: there is an afterCommit hook that you can hook into on the transaction object itself.

    Knowing this isn't directly related to model hooks, the usefulness will be dependent on use case.

  22. papb commented on Jan 23, 2020

    @papb
    Member

    Hi @bradley, thanks for your comment, can you please open a new docs issue requesting this to be made explicit somehow at the docs? You can link to your comment here. Thanks.

  23. marcin-wlodarczyk commented on Aug 11, 2021

    @marcin-wlodarczyk

    I had a similar problem and couldn't find explicit documentation about afterCommit hook.

    I rely on global model hooks to dispatch events from the queue. The problem consisted of events dispatched even after transaction failure.

    My solution:

    // Global Hook
    model.afterCreate((model, options) => {
        if (options.transaction) {
            // Wait until transaction is committed
            options.transaction.afterCommit(() => {
                // Dispatch events (model is persisted in database)
            });
        } else {
            // Optionally dispatch events outside of transaction
        }
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions