Skip to content

Instantly share code, notes, and snippets.

@kivi
Created September 4, 2012 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kivi/3620910 to your computer and use it in GitHub Desktop.
Save kivi/3620910 to your computer and use it in GitHub Desktop.
Wip for using validator within sequelize, when creating or modifying.
// if an array with field names is passed to save()
// only those fields will be updated
DAO.prototype.save = function(fields) {
var self = this
, values = fields ? {} : this.values
, updatedAtAttr = this.__options.underscored ? 'updated_at' : 'updatedAt'
, createdAtAttr = this.__options.underscored ? 'created_at' : 'createdAt'
// --- validation START
var validation_errors = self.validate();
if (validation_errors !== null) {
return new Utils.CustomEventEmitter(function(emitter) {
setTimeout( function() {
emitter.emit('error', validation_errors);
}, 100);
}).run();
}
// --- validation END
if(fields) {
if(self.__options.timestamps) {
if(fields.indexOf(updatedAtAttr) === -1) {
fields.push(updatedAtAttr)
}
if(fields.indexOf(createdAtAttr) === -1) {
fields.push(createdAtAttr)
}
}
fields.forEach(function(field) {
if(self.values[field] !== undefined) {
values[field] = self.values[field]
}
})
}
if(this.__options.timestamps && this.hasOwnProperty(updatedAtAttr)) {
var now = new Date()
this[updatedAtAttr] = now
values[updatedAtAttr] = now
}
if(this.isNewRecord) {
return this.QueryInterface.insert(this, this.__factory.tableName, values)
} else {
var identifier = this.__options.hasPrimaryKeys ? this.primaryKeyValues : this.id
, tableName = this.__factory.tableName
, query = this.QueryInterface.update(this, tableName, values, identifier)
return query
}
}
@janmeier
Copy link

janmeier commented Sep 4, 2012

The event emitter is for handling asynchronous callbacks, and since validations are not async you shouldn't create one. I was thinking something like:

var validation_errors = self.validate();

if (validation_errors !== null) {
  return new Utils.CustomEventEmitter(function(emitter) {
    emitter.emit('erorr', validation_erorrs);
  }).run();
};

The reason you are returning an eventEmitter is that the user expects something that he can call done, error etc. on. But the emitter should only be created if there is an actual error to emit.

I'm not sure about race-conditions here - emit might be called before the .error callback can be attached, but try this and if it doesn't work wrap the body of the emit function in a setTimeout

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment