loopback icon indicating copy to clipboard operation
loopback copied to clipboard

Access to parent instance from 'before delete' of embedsMany model

Open frankorama opened this issue 9 years ago • 5 comments

Description/Steps to reproduce

I have 2 models setup in an embedsMany relationship such that ParentModel (base: PersistedModel) embeds many ChildModels (base: Model)

This creates the usual api methods, including the delete method for a child instance: DELETE /parent-model/{id}/child-model/{fk}

I have a before delete operation hook on my child model. When I call the delete method, the before delete hook is called, but I have no way of knowing what the parent instance is. I would like to perform some security checks on data in the parent, but can not easily access it:

ChildModel.observe('before delete', (ctx, next)=>{
  // ctx.instance = child being deleted
  // ctx.Model = ChildModel
  // ctx.options = options object with accessToken

  // How do I get the child's parent from here?

  next();
});

Expected result

Would like to have a reference to the parent object in the context object. Just the ID, or the whole object so I can validate some data before going forward with the delete. ctx.parent // parent instance ctx.parentId // id of parent instance

Additional information

frankorama avatar Feb 25 '17 11:02 frankorama

Hi @frankorama, thank you for the feature request, would you like to contribute the implementation yourself?

IMO, the parent instance should be ideally available via ctx.instance - that way the parent can be access from other places, e.g. from custom (remote) methods. I think the implementation of this feature may be easier/small that way too.

bajtos avatar Mar 01 '17 14:03 bajtos

I was able to achieve the same thing in

https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/relation-definition.js#L2100

this function I added

inst.parent = -> 
  modelInstance 

so you could access the parent instance by using parent = @parent()

may help, cheers

BoLaMN avatar Mar 02 '17 18:03 BoLaMN

Hi there, I'm having issues with the embedsMany, I need to put some logic like

CustomerAddress.observe('before save', (ctx, next) => {
// need to retrieve the parent data here in order to do some calculations before saving the child.

});

My model definition:

{
    "name": "Customer",
    "plural": "Customers",
    "base": "PersistedModel",
    "idInjection": true,
    "options": {
        "validateUpsert": true
    },
    "properties": {
        "dob": {
            "type": "date",
            "required": false
        }
    },
    "validations": [],
    "relations": {
        "address": {
            "type": "embedsMany",
            "model": "CustomerAddress",
            "property": "address",
            "options": {
                "validate": true,
                "persistent": true
            }
        }
        }
    },
    "acls": [],
    "methods": {}
}

I'm really lost trying to figure out to do that.

@superkhau

lzerma avatar Apr 20 '17 09:04 lzerma

@Izerma Can you try:

var app = require('../../server/server');
...
CustomerAddress.observe('before save', (ctx, next) => {
  var Customer = app.models.Customer;
  Customer.app.models.Customer.find(...)
});

See http://loopback.io/doc/en/lb2/Working-with-LoopBack-objects.html#from-a-model-script

superkhau avatar Apr 20 '17 20:04 superkhau

Hey,

This issue was closed but nothing was made about it. I think that feature is still useful.

I've been poking around the code and we already have all that is needed to make this possible.

I want access to the parent on the 'before save' hook. To do that I went to loopback-datasource-juggler/lib/relation-definition.js and on EmbedsMany.prototype.create, for example, var modelInstance = this.modelInstance; is the parent instance.

So if we include that to the context a few lines down, we have access to the parent instance. Something like this:

var context = {
    Model: modelTo,
    parentInstance: modelInstance,// Added parent to context
    instance: inst,
    options: options || {},
    hookState: {},
    };
    modelTo.notifyObserversOf('before save', context, function(err) {
    if (err) return cb(err);
    updateEmbedded(function(err, inst) {
        if (err) return cb(err, null);
        modelTo.notifyObserversOf('after save', context, function(err) {
        cb(err, err ? null : inst);
        });
    });
});

israelglar avatar Jul 12 '18 13:07 israelglar