Search code examples
loopbackjsstrongloop

Loopback: getting model changes inside model hook


On model PUT, I need to make custom validation, based on its original value. Inside beforeUpdate model hook I can access 'next' function, 'request body' object (as beforeUpdate arguments) and updated model itself via 'this' keyword.

Is there any way to get pristine model or its changes, without querying it from DB?

Is it even possible to update current model inside model hooks (because changing 'this' properties doesn't take effect)?


Solution

  • Disclaimer: I am a LoopBack developer.

    Is there any way to get pristine model or its changes, without querying it from DB?

    No, that's not possible.

    Take a look at the code of updateAttributes() in loopback-datasource-juggler/lib/dao.js, which is called when you make a request to PUT /models/:id:

    inst.setAttributes(data);
    
    inst.isValid(function (valid) {
      if (!valid) {
        if (cb) {
          cb(new ValidationError(inst), inst);
        }
      } else {
        inst.trigger('save', function (saveDone) {
          inst.trigger('update', function (done) {
            // etc.
    

    The model is updated before executing any hooks.