不要怂,就是干,撸起袖子干!

Commit 8f572eb2 by Daniel Durante

bulkCreate() now has a third argument which gives you the ability to validate ea…

…ch row before attempting to bulkInsert.
1 parent 9a41b4ae
Showing with 56 additions and 2 deletions
...@@ -434,11 +434,30 @@ module.exports = (function() { ...@@ -434,11 +434,30 @@ module.exports = (function() {
* generated IDs and other default values in a way that can be mapped to * generated IDs and other default values in a way that can be mapped to
* multiple records * multiple records
*/ */
DAOFactory.prototype.bulkCreate = function(records, fields) { DAOFactory.prototype.bulkCreate = function(records, fields, options) {
options = options || {}
options.validate = options.validate || false
var self = this var self = this
, daos = records.map(function(v) { return self.build(v) })
, updatedAtAttr = self.options.underscored ? 'updated_at' : 'updatedAt' , updatedAtAttr = self.options.underscored ? 'updated_at' : 'updatedAt'
, createdAtAttr = self.options.underscored ? 'created_at' : 'createdAt' , createdAtAttr = self.options.underscored ? 'created_at' : 'createdAt'
, errors = []
, daos = records.map(function(v) {
var build = self.build(v)
if (options.validate === true) {
var valid = build.validate({type: 'insert'})
if (valid !== null) {
errors[errors.length] = {record: v, errors: valid}
}
}
return build
})
if (options.validate === true && errors.length > 0) {
return new Utils.CustomEventEmitter(function(emitter) {
emitter.emit('error', errors)
}).run()
}
fields = fields || [] fields = fields || []
......
...@@ -715,6 +715,41 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () { ...@@ -715,6 +715,41 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
}) })
}) })
it('emits an error when validate is set to true', function(done) {
var Tasks = this.sequelize.define('Task', {
name: {
type: Sequelize.STRING,
validate: {
notNull: { args: true, msg: 'name cannot be null' }
}
},
code: {
type: Sequelize.STRING,
validate: {
len: [3, 10]
}
}
})
Tasks.sync({ force: true }).success(function() {
Tasks.bulkCreate([
{name: 'foo', code: '123'},
{code: '1234'},
{name: 'bar', code: '1'}
], null, {validate: true}).error(function(errors) {
expect(errors).to.not.be.null
expect(errors).to.be.instanceof(Array)
expect(errors).to.have.length(2)
expect(errors[0].record.code).to.equal('1234')
expect(errors[0].errors.name[0]).to.equal('name cannot be null')
expect(errors[1].record.name).to.equal('bar')
expect(errors[1].record.code).to.equal('1')
expect(errors[1].errors.code[0]).to.equal('String is not in range: code')
done()
})
})
})
describe('enums', function() { describe('enums', function() {
it('correctly restores enum values', function(done) { it('correctly restores enum values', function(done) {
var self = this var self = this
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!