Created
September 4, 2012 12:53
-
-
Save kivi/3620910 to your computer and use it in GitHub Desktop.
Wip for using validator within sequelize, when creating or modifying.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The event emitter is for handling asynchronous callbacks, and since validations are not async you shouldn't create one. I was thinking something like:
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