adonisjs / lucid

AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more
https://lucid.adonisjs.com/
MIT License
1.07k stars 191 forks source link

Provide query instance in `after` hooks #943

Closed ndianabasi closed 10 months ago

ndianabasi commented 1 year ago

Proposed changes

This PR injects the ModelQueryBuilder instance into the Model after hooks.

A use case for having the query instance available in the after hooks is for cleaning up changes to the model's class properties.

Example:

// Mixin

export const SoftDeletable: SoftDeletableMixin = (superclass) => {
  class SoftDeletableModel extends superclass {
    public static $showDeleted = false

    @beforeFind()
    public static ignoreDeletedOnFind(
      query: ModelQueryBuilderContract<ReturnType<SoftDeletableMixin>>
    ) {
      if (!query.model.$showDeleted) {
        query.where(`${query.model.table}.is_soft_deleted`, false)
      }
    }

    @beforeFetch()
    public static ignoreDeletedOnFetch(
      query: ModelQueryBuilderContract<ReturnType<SoftDeletableMixin>>
    ) {
      if (!query.model.$showDeleted) {
        query.where(`${query.model.table}.is_soft_deleted`, false)
      }
    }

    @afterFind()
    public static resetDeletedAfterFind(_, query) {
      // This does not work
      // this.$showDeleted = false

      // This works
      query.model.$showDeleted = false
    }

    @afterFetch()
    public static resetDeletedAfterFetch(_, query) {
      query.model.$showDeleted = false
    }

    @afterPaginate()
    public static resetDeletedAfterPaginate(_, query) {
      query.model.$showDeleted = false
    }
  }

  return SoftDeletableModel
}

Types of changes

What types of changes does your code introduce?

Put an x in the boxes that apply

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

Further comments

If this is a relatively large or complex change, kick off the discussion by explaining why you chose the solution you did and what alternatives you considered, etc...

thetutlage commented 1 year ago

Since, this is going to be a big change (in terms of design). I will not be able to merge it right away.

Also, we have some plans around restructuring the hooks API, so I have to see how this change plays with that restructuring.

I will keep the PR on hold for now

ndianabasi commented 1 year ago

Thanks for considering it.

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.