loopback-next icon indicating copy to clipboard operation
loopback-next copied to clipboard

Spike: Operation hooks for models/repositories

Open bajtos opened this issue 8 years ago • 34 comments

In LoopBack 3.x, we have a concept of Operation Hooks allowing models to register handlers for common events: access, before/after save, before/after delete, load/persist.

We should provide similar functionality in LoopBack 4 too.

See also the discussion in #1857 which triggered this feature request.

/cc @vvdwivedi @David-Mulder @marioestradarosa @raymondfeng

Acceptance criteria

  • [ ] A draft pull request that:
    • finds out the minimum infrastructure and what other use cases would use this hook
    • see if use cases can be handled by life cycle observers(for data events) or interceptors
    • high level proposal for the hooks in the repository level
    • finds out that which kind of hooks are more suitable for LB4: a set of hooks that is universal for all possible implementations of a given repository interface, or the hooks coupled with a particular repository implementation. ( e.g different sets of hooks for key/value and CRUD)

bajtos avatar Oct 26 '18 06:10 bajtos

As a temporary workaround, it's possible to leverage existing LB 3.x Operation Hooks in the custom per-model repository class. An example:

export class MyModelRepository extends DefaultCrudRepository<
  MyModel,
  typeof MyModel.prototype.id
> {
  constructor(@inject('datasources.db') dataSource: juggler.DataSource) {
    super(MyModel, dataSource);

    (this.modelClass as any).observe('persist', async (ctx: any) => {
      delete ctx.data.computed;
    });
  }
}

@bajtos Is the MyModel only can be a LoopBack 4 model? Can this approach compatible with LoopBack 3 models in lb3app/server/models?

https://loopback.io/doc/en/lb3/Operation-hooks.html

FottyM avatar Aug 14 '20 06:08 FottyM

As a temporary workaround, it's possible to leverage existing LB 3.x Operation Hooks in the custom per-model repository class.

An example:

export class MyModelRepository extends DefaultCrudRepository<
  MyModel,
  typeof MyModel.prototype.id
> {
  constructor(@inject('datasources.db') dataSource: juggler.DataSource) {
    super(MyModel, dataSource);

    (this.modelClass as any).observe('persist', async (ctx: any) => {
      delete ctx.data.computed;
    });
  }
}

Operation hook in LB3 can access httpContext through ctx.options.httpContext. But in this workaround ctx.options is {}. @inject doesn't work as DI cannot be applied to listener function parameter. I am stuck.

Being able to access httpContext is necessary in my use case.

f-w avatar Sep 08 '20 20:09 f-w

Operation hook in LB3 can access httpContext through ctx.options.httpContext. But in this workaround ctx.options is {}. @inject doesn't work as DI cannot be applied to listener function parameter. I am stuck.

Being able to access httpContext is necessary in my use case.

@f-w You could try injecting a getter function for RestBindings.Http.CONTEXT in your model repository constructor method and get its value when the hook is triggered:

export class MyModelRepository extends DefaultCrudRepository<
  MyModel,
  typeof MyModel.prototype.id
> {
  constructor(
    @inject('datasources.db') dataSource: juggler.DataSource,
// -> GETTER
    @inject.getter(RestBindings.Http.CONTEXT) protected getHttpContext: Getter<Context>,
// <------
  ) {
    super(MyModel, dataSource);

    (this.modelClass as any).observe('persist', async (ctx: any) => {
// -> GETTER VALUE
      const httpCtx = await this.getHttpContext();
      console.log(httpCtx);
// <------
      delete ctx.data.computed;
    });
  }
}

tipuban avatar Sep 13 '20 15:09 tipuban

The above unfortunately gives us a context not found error

Cannot start the application. ResolutionError: The key 'rest.http.request' is not bound to any value in context ApiServerApplication-YHAq-QSFTE_VUeFcZFYo6g-0 (context: ApiServerApplication-YHAq-QSFTE_VUeFcZFYo6g-0, binding: rest.http.request, resolutionPath: repositories.SomeRepository --> @SomeRepository.prototype.request)
    at ApiServerApplication.getValueOrPromise

puranjayjain-mtxb2b avatar Sep 13 '20 21:09 puranjayjain-mtxb2b

Thanks, it worked for me, but not in the migration script, so ended up injecting an env variable to guard it.

puranjayjain-mtxb2b avatar Sep 13 '20 22:09 puranjayjain-mtxb2b

I would like to use this workaround to edit the query. The problem is that the listener is created for every request.

(this.modelClass as any).observe('access', async (ctx: any) => {
        console.log('this is a leak.')
});

First request you will see one console log, second request you see two more. Also, as I modify the query, it grows with every "access", ctx.query.where = { and: [ctx.query.where, myAdditionalRestrictions] };, it seems like the ctx is shared among instances.

How to solve this?

mycolaos avatar Oct 15 '20 18:10 mycolaos

Found this https://loopback.io/doc/en/lb4/migration-models-operation-hooks.html,

class ProductRepository extends DefaultCrudRepository<
  Product,
  typeof Product.prototype.id,
  ProductRelations
> {
  constructor(dataSource: juggler.DataSource) {
    super(Product, dataSource);
  }

  definePersistedModel(entityClass: typeof Product) {
    const modelClass = super.definePersistedModel(entityClass);
    modelClass.observe('before save', async ctx => {
      console.log(`going to save ${ctx.Model.modelName}`);
    });
    return modelClass;
  }
}

Seems to work. Is there any reason why the other approach was recommended?

UPDATE: not really working, it keeps the reference to the first RequestContext.

mycolaos avatar Oct 15 '20 18:10 mycolaos

I'm facing a similar issue: I need to get the authenticated user (@inject(SecurityBindings.USER)) from within the model observer in order to secure access to data & auto-magically assign entity ownership & other security-related attributes on entity save, however I can't get the authenticated user since the observer is running in an APPLICATION context and the user gets authenticated in a REQUEST context. I've been struggling with this for days now.

I've tried using my own JWTAuthenticationProvider in order to bind the user to the application context but that's going to cause trouble when multiple users hit the app at the same time since the APPLICATION context is a singleton.

Does anybody have any suggestions on how to get the REQUEST context from within an observer callback? Any help would be much appreciated.

tipuban avatar Oct 16 '20 09:10 tipuban

I'm actually considering creating a custom sequence where I bind model operation hooks for this request only, and then unbind them once the request is completed. Does that sound like a good idea? Or does anybody have a better suggestion?

tipuban avatar Oct 16 '20 10:10 tipuban

Nevermind. I figured out I can use Global Interceptors to bind/unbind my model observers :).

tipuban avatar Oct 16 '20 11:10 tipuban

Found this https://loopback.io/doc/en/lb4/migration-models-operation-hooks.html,

class ProductRepository extends DefaultCrudRepository<
  Product,
  typeof Product.prototype.id,
  ProductRelations
> {
  constructor(dataSource: juggler.DataSource) {
    super(Product, dataSource);
  }

  definePersistedModel(entityClass: typeof Product) {
    const modelClass = super.definePersistedModel(entityClass);
    modelClass.observe('before save', async ctx => {
      console.log(`going to save ${ctx.Model.modelName}`);
    });
    return modelClass;
  }
}

Seems to work. Is there any reason why the other approach was recommended?

UPDATE: not really working, it keeps the reference to the first RequestContext.

I also confirmed the workaround keeps the reference to the request context defined in the first repository instance. For example, with code

export class ProductRepository extends DefaultCrudRepository<
  Product,
  typeof Product.prototype.id
> {
  constructor(
   ...
    @inject.getter(MiddlewareBindings.CONTEXT)
    protected getHttpContext: Getter<MiddlewareContext>,
  ) {
    ...
  }

  definePersistedModel(
    entityClass: typeof Product,
  ): typeof juggler.PersistedModel {
    const modelClass = super.definePersistedModel(entityClass);
    modelClass.observe('access', async ctx => {
      const httpCtx = await this.getHttpContext();
      console.log(httpCtx);
    });
    return modelClass;
  }
}
  1. Subsequent http requests use the httpCtx of the first request
  2. In a test, when first inserting items using the repository (which has no http context), then querying using super test client, the httpCtx of the query request is null.

Not only this is not working, but also poses security vulnerability. Please remove https://loopback.io/doc/en/lb4/migration-models-operation-hooks.html.

f-w avatar Dec 29 '20 04:12 f-w

Thanks for providing your detailed findings, looking into this right now.


These are my preliminary findings:

  1. Subsequent http requests use the httpCtx of the first request
  2. In a test, when first inserting items using the repository (which has no http context), then querying using super test client, the httpCtx of the query request is null.

I have not been able to replicate this. In my testing, this has always resulted in a key 'xxx' is not bound to any value error.

I have tested and gotten the aforementioned behaviour with these bindings:

  • RestBIndings.Http.REQUEST
  • MiddlewareBindings.CONTEXT

To help expedite this, I've created issue #6962, quoting the relevant comments.

Could you please add additional information and a GitHub repo with a minium-reproduction example into issue #6962 so that we can pinpoint the issue?

achrinza avatar Dec 29 '20 13:12 achrinza

This issue has been marked stale because it has not seen activity within six months. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository. This issue will be closed within 30 days of being stale.

stale[bot] avatar Jul 14 '21 04:07 stale[bot]

This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.

stale[bot] avatar Aug 13 '21 05:08 stale[bot]