Search code examples
node.jsgeddy

Manipulating data before save with geddy


I have a few scenarios in my application where I need to manipulate the data before it is saved.

I have a CakePHP background so this I would normally do in a Model's beforeSave method.

Is there anything equivalent that I can do in my models in geddy?


Solution

  • Check out the Model events.

    Both the base model 'constructors,' and model instances are EventEmitters. The emit events during the create/update/remove lifecycle of model instances. In all cases, the plain-named event is fired after the event in question, and the 'before'-prefixed event, of course happens before.

    The 'constructor' for a model emits the following events:

    • beforeCreate
    • create
    • beforeValidate
    • validate
    • beforeUpdateProperties
    • updateProperties
    • beforeSave (new instances, single and bulk)
    • save (new instances, single and bulk)
    • beforeUpdate (existing single instances, bulk updates)
    • update (existing single instances, bulk updates)
    • beforeRemove remove

    For example:

    var MyModel = function () { ... };
    
    MyModel = geddy.model.register('MyModel', MyModel);
    
    MyModel.on('beforeSave', function(data){
       console.log(data);
    })