Add metadata to DS.Model.save()


#1

Hello,

What would be the best way to update an object and at the same time let the backend know about an additional operation that it should do?

For example: I want to update the email of a User object.

user.email = 'newEmail@domain.com';
user.save();

When the backend sees that the email has been updated, it must additionally send an email address to the user notifying him of the change. But the email must be sent only when the email field changes, not other fields.

I could make an initial query in the database and then for each field in the user table, figure out what changed. But if I have a lot of fields, code on the backend gets messy.

I would prefer something like the following:

user.email = 'newEmail@domain.com';
var meta = {operation: 'changeEmail'};
user.save(meta);

Now there’s a way to tell the backend exactly which fields have changed and it will know to make additional operations if needed.

Is there any way to do this? Do you think this addition to Ember Data makes sense?

I’ve seen other people ask something similar on StackOverflow, but this solution doesn’t work with the latest Ember Data anymore.

Thanks!


#2

First, I don’t know, so only continue if you want my unsolicited opinion:

This really does seem (to me) to be something you would want to keep in the backend, for a couple reasons: 1) Suppose the update fails—you’ll need logic not to fire the action you sent, 2) suppose you decide to add additional operations to the “change Email” event—you’ll end up writing that same logic into a parent function, and 3) if you ever change the front end, or add another client (mobile app, etc.) you’ll need to make sure they are sending the same metadata.

If you happen to be using Mongoose/MogoDB, for example, you can just use something like the .pre('save' … ) hook. I’m using this to salt and hash passwords:

/* Password Hash and Verification */
userSchema.pre('save', function(next) {
  var user = this;

    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next();

    // generate a salt etc.
    
    . . . 

  });

You should be able to—fairly simply—add some logic to fire off an email. I’m sure other ORMs have similar features, if you aren’t using Mongoose.

My (unsolicited) two cents.

Good luck