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

Commit a1c6f16d by Erik Seliger Committed by Simon Schick

refactor(model): remove build in favor or constructor usage (#10852)

BREAKING CHANGE:

`Model.build` has been removed. Use `Model.bulkBuild` or `new Model` instead.

Co-authored-by: Simon Schick <demwizzy@gmail.com>
1 parent b9338669
Showing with 243 additions and 259 deletions
......@@ -5,12 +5,12 @@
In order to create instances of defined classes just do as follows&period; You might recognize the syntax if you coded Ruby in the past&period; Using the `build`-method will return an unsaved object&comma; which you explicitly have to save&period;
```js
const project = Project.build({
const project = new Project({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
})
const task = Task.build({
const task = new Task({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
......@@ -28,7 +28,7 @@ Task.init({
}, { sequelize, modelName: 'task' });
// now instantiate an object
const task = Task.build({title: 'very important task'})
const task = new Task({title: 'very important task'})
task.title // ==> 'very important task'
task.rating // ==> 3
......@@ -46,8 +46,7 @@ task.save().catch(error => {
})
// you can also build, save and access the object with chaining:
Task
.build({ title: 'foo', description: 'bar', deadline: new Date() })
new Task({ title: 'foo', description: 'bar', deadline: new Date() })
.save()
.then(anotherTask => {
// you can now access the currently saved task with the variable anotherTask... nice!
......@@ -59,7 +58,7 @@ Task
## Creating persistent instances
While an instance created with `.build()` requires an explicit `.save()` call to be stored in the database&comma; `.create()` omits that requirement altogether and automatically stores your instance's data once called.
While an instance created with `new` requires an explicit `.save()` call to be stored in the database&comma; `.create()` omits that requirement altogether and automatically stores your instance's data once called.
```js
Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(task => {
......
......@@ -676,7 +676,7 @@ class User extends Model {
User.init({ firstname: Sequelize.STRING, lastname: Sequelize.STRING }, { sequelize });
// Example:
User.build({ firstname: 'foo', lastname: 'bar' }).getFullname() // 'foo bar'
new User({ firstname: 'foo', lastname: 'bar' }).getFullname() // 'foo bar'
```
### Indexes
......
......@@ -18,3 +18,9 @@ Please refer to previous changelogs for the migration guide.
If you have relied on accessing sequelize operators via `Symbol.for('gt')` etc. you must now prefix them with `sequelize.operator` eg.
`Symbol.for('sequelize.operator.gt')`
### Removed `Model.build`
`Model.build` has been acting as proxy for `bulkBuild` and `new Model` for a while.
Use `Model.bulkBuild` or `new Model` instead.
......@@ -128,7 +128,7 @@ class Association {
const tmpInstance = {};
tmpInstance[this.target.primaryKeyAttribute] = element;
return this.target.build(tmpInstance, { isNewRecord: false });
return new this.target(tmpInstance, { isNewRecord: false });
});
}
......
......@@ -217,7 +217,7 @@ class HasOne extends Association {
if (!(associatedInstance instanceof this.target)) {
const tmpInstance = {};
tmpInstance[this.target.primaryKeyAttribute] = associatedInstance;
associatedInstance = this.target.build(tmpInstance, {
associatedInstance = new this.target(tmpInstance, {
isNewRecord: false
});
}
......
......@@ -2144,24 +2144,15 @@ class Model {
}
/**
* Builds a new model instance.
* Builds multiple models in one operation.
*
* @param {Object|Array} values An object of key value pairs or an array of such. If an array, the function will return an array of instances.
* @param {Object} [options] Instance build options
* @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
* @param {boolean} [options.isNewRecord=true] Is this new record
* @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set`
* @param {Array<Object>} valueSets An object of key value pairs or an array of such. If an array, the function will return an array of instances.
* @param {Object} [options] Instance build options,
* @see
* {@link constructor}
*
* @returns {Model|Array<Model>}
* @returns {Array<Model>}
*/
static build(values, options) {
if (Array.isArray(values)) {
return this.bulkBuild(values, options);
}
return new this(values, options);
}
static bulkBuild(valueSets, options) {
options = Object.assign({
isNewRecord: true
......@@ -2179,14 +2170,14 @@ class Model {
options.attributes = options.attributes.map(attribute => Array.isArray(attribute) ? attribute[1] : attribute);
}
return valueSets.map(values => this.build(values, options));
return valueSets.map(values => new this(values, options));
}
/**
* Builds a new model instance and calls save on it.
* @see
* {@link Model.build}
* {@link Model.constructor}
* @see
* {@link Model.save}
*
......@@ -2212,7 +2203,7 @@ class Model {
static create(values, options) {
options = Utils.cloneDeep(options);
return this.build(values, {
return new this(values, {
isNewRecord: true,
attributes: options.fields,
include: options.include,
......@@ -2249,12 +2240,12 @@ class Model {
values = Utils.defaults(values, options.where);
}
instance = this.build(values, options);
instance = new this(values, options);
return Promise.resolve([instance, true]);
return [instance, true];
}
return Promise.resolve([instance, false]);
return [instance, false];
});
}
......@@ -2443,7 +2434,7 @@ class Model {
const createdAtAttr = this._timestampAttributes.createdAt;
const updatedAtAttr = this._timestampAttributes.updatedAt;
const hasPrimary = this.primaryKeyField in values || this.primaryKeyAttribute in values;
const instance = this.build(values);
const instance = new this(values);
if (!options.fields) {
options.fields = Object.keys(instance._changed);
......@@ -2565,7 +2556,7 @@ class Model {
const updatedAtAttr = this._timestampAttributes.updatedAt;
const now = Utils.now(this.sequelize.options.dialect);
let instances = records.map(values => this.build(values, { isNewRecord: true }));
let instances = records.map(values => new this(values, { isNewRecord: true }));
return Promise.try(() => {
// Run before hook
......@@ -2929,7 +2920,7 @@ class Model {
return Promise.try(() => {
// Validate
if (options.validate) {
const build = this.build(values);
const build = new this(values);
build.set(this._timestampAttributes.updatedAt, values[this._timestampAttributes.updatedAt], { raw: true });
if (options.sideEffects) {
......@@ -3405,7 +3396,7 @@ class Model {
*
* Set can also be used to build instances for associations, if you have values for those.
* When using set with associations you need to make sure the property key matches the alias of the association
* while also making sure that the proper include options have been set (from .build() or .findOne())
* while also making sure that the proper include options have been set (from the constructor or .findOne())
*
* If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
*
......@@ -3627,7 +3618,7 @@ class Model {
value = value[0];
}
isEmpty = value && value[primaryKeyAttribute] === null || value === null;
this[accessor] = this.dataValues[accessor] = isEmpty ? null : include.model.build(value, childOptions);
this[accessor] = this.dataValues[accessor] = isEmpty ? null : new include.model(value, childOptions);
} else {
isEmpty = value[0] && value[0][primaryKeyAttribute] === null;
this[accessor] = this.dataValues[accessor] = isEmpty ? [] : include.model.bulkBuild(value, childOptions);
......
......@@ -521,7 +521,7 @@ class Sequelize {
*
* @returns {Promise}
*
* @see {@link Model.build} for more information about instance option.
* @see {@link Model.constructor} for more information about instance option.
*/
query(sql, options) {
......
......@@ -2206,8 +2206,8 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
});
it('correctly uses bId in A', function() {
const a1 = this.A.build({ name: 'a1' }),
b1 = this.B.build({ name: 'b1' });
const a1 = new this.A({ name: 'a1' }),
b1 = new this.B({ name: 'b1' });
return a1
.save()
......@@ -2230,8 +2230,8 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
});
it('correctly uses bId in A', function() {
const a1 = this.A.build({ name: 'a1' }),
b1 = this.B.build({ name: 'b1' });
const a1 = new this.A({ name: 'a1' }),
b1 = new this.B({ name: 'b1' });
return a1
.save()
......@@ -2328,9 +2328,9 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
});
it('correctly sets user and owner', function() {
const p1 = this.Project.build({ projectName: 'p1' }),
u1 = this.User.build({ name: 'u1' }),
u2 = this.User.build({ name: 'u2' });
const p1 = new this.Project({ projectName: 'p1' }),
u1 = new this.User({ name: 'u1' }),
u2 = new this.User({ name: 'u2' });
return p1
.save()
......
......@@ -33,7 +33,7 @@ if (dialect === 'sqlite') {
describe('findAll', () => {
it('handles dates correctly', function() {
const user = this.User.build({ username: 'user' });
const user = new this.User({ username: 'user' });
user.dataValues.createdAt = new Date(2011, 4, 4);
......
......@@ -72,13 +72,13 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
describe('isNewRecord', () => {
it('returns true for non-saved objects', function() {
const user = this.User.build({ username: 'user' });
const user = new this.User({ username: 'user' });
expect(user.id).to.be.null;
expect(user.isNewRecord).to.be.ok;
});
it('returns false for saved objects', function() {
return this.User.build({ username: 'user' }).save().then(user => {
return new this.User({ username: 'user' }).save().then(user => {
expect(user.isNewRecord).to.not.be.ok;
});
});
......@@ -119,19 +119,19 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
describe('default values', () => {
describe('uuid', () => {
it('should store a string in uuidv1 and uuidv4', function() {
const user = this.User.build({ username: 'a user' });
const user = new this.User({ username: 'a user' });
expect(user.uuidv1).to.be.a('string');
expect(user.uuidv4).to.be.a('string');
});
it('should store a string of length 36 in uuidv1 and uuidv4', function() {
const user = this.User.build({ username: 'a user' });
const user = new this.User({ username: 'a user' });
expect(user.uuidv1).to.have.length(36);
expect(user.uuidv4).to.have.length(36);
});
it('should store a valid uuid in uuidv1 and uuidv4 that conforms to the UUID v1 and v4 specifications', function() {
const user = this.User.build({ username: 'a user' });
const user = new this.User({ username: 'a user' });
expect(isUUID(user.uuidv1)).to.be.true;
expect(isUUID(user.uuidv4, 4)).to.be.true;
});
......@@ -150,7 +150,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
}
});
const person = Person.build({});
const person = new Person({});
expect(person.id1).to.be.ok;
expect(person.id1).to.have.length(36);
......@@ -160,14 +160,14 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
describe('current date', () => {
it('should store a date in touchedAt', function() {
const user = this.User.build({ username: 'a user' });
const user = new this.User({ username: 'a user' });
expect(user.touchedAt).to.be.instanceof(Date);
});
it('should store the current date in touchedAt', function() {
const clock = sinon.useFakeTimers();
clock.tick(5000);
const user = this.User.build({ username: 'a user' });
const user = new this.User({ username: 'a user' });
clock.restore();
expect(+user.touchedAt).to.be.equal(5000);
});
......@@ -175,7 +175,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
describe('allowNull date', () => {
it('should be just "null" and not Date with Invalid Date', function() {
return this.User.build({ username: 'a user' }).save().then(() => {
return new this.User({ username: 'a user' }).save().then(() => {
return this.User.findOne({ where: { username: 'a user' } }).then(user => {
expect(user.dateAllowNullTrue).to.be.null;
});
......@@ -184,7 +184,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
it('should be the same valid date when saving the date', function() {
const date = new Date();
return this.User.build({ username: 'a user', dateAllowNullTrue: date }).save().then(() => {
return new this.User({ username: 'a user', dateAllowNullTrue: date }).save().then(() => {
return this.User.findOne({ where: { username: 'a user' } }).then(user => {
expect(user.dateAllowNullTrue.toString()).to.equal(date.toString());
});
......@@ -194,7 +194,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
describe('super user boolean', () => {
it('should default to false', function() {
return this.User.build({
return new this.User({
username: 'a user'
})
.save()
......@@ -211,7 +211,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should override default when given truthy boolean', function() {
return this.User.build({
return new this.User({
username: 'a user',
isSuperUser: true
})
......@@ -229,7 +229,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should override default when given truthy boolean-string ("true")', function() {
return this.User.build({
return new this.User({
username: 'a user',
isSuperUser: 'true'
})
......@@ -247,7 +247,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should override default when given truthy boolean-int (1)', function() {
return this.User.build({
return new this.User({
username: 'a user',
isSuperUser: 1
})
......@@ -267,7 +267,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
it('should throw error when given value of incorrect type', function() {
let callCount = 0;
return this.User.build({
return new this.User({
username: 'a user',
isSuperUser: 'INCORRECT_VALUE_TYPE'
})
......@@ -579,7 +579,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
}, { timestamps: false, logging: false });
return User.sync().then(() => {
const user = User.build({ username: 'foo' });
const user = new User({ username: 'foo' });
expect(user.get({ plain: true })).to.deep.equal({ username: 'foo', id: null });
});
});
......
......@@ -279,8 +279,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
});
it('should emit an error when we try to enter in a string for an auto increment key through .build().validate()', function() {
const user = this.User.build({ id: 'helloworld' });
it('should emit an error when we try to enter in a string for an auto increment key through new Model().validate()', function() {
const user = new this.User({ id: 'helloworld' });
return expect(user.validate()).to.be.rejected.then(err => {
expect(err.get('id')[0].message).to.equal('ID must be an integer!');
......@@ -288,7 +288,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
it('should emit an error when we try to .save()', function() {
const user = this.User.build({ id: 'helloworld' });
const user = new this.User({ id: 'helloworld' });
return user.save().catch(err => {
expect(err).to.be.an.instanceOf(Error);
expect(err.get('id')[0].message).to.equal('ID must be an integer!');
......@@ -395,13 +395,13 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
const failingUser = User.build({ name: '3' });
const failingUser = new User({ name: '3' });
return expect(failingUser.validate()).to.be.rejected.then(error => {
expect(error).to.be.an.instanceOf(Error);
expect(error.get('name')[0].message).to.equal("name should equal '2'");
const successfulUser = User.build({ name: '2' });
const successfulUser = new User({ name: '2' });
return expect(successfulUser.validate()).not.to.be.rejected;
});
});
......@@ -424,11 +424,11 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
return User.sync().then(() => {
return expect(User.build({ name: 'error' }).validate()).to.be.rejected.then(error => {
return expect(new User({ name: 'error' }).validate()).to.be.rejected.then(error => {
expect(error).to.be.instanceof(Sequelize.ValidationError);
expect(error.get('name')[0].message).to.equal('Invalid username');
return expect(User.build({ name: 'no error' }).validate()).not.to.be.rejected;
return expect(new User({ name: 'no error' }).validate()).not.to.be.rejected;
});
});
});
......@@ -444,8 +444,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(User
.build({ age: -1 })
return expect(new User({ age: -1 })
.validate())
.to.be.rejected
.then(error => {
......@@ -473,15 +472,13 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(Foo
.build({ field1: null, field2: null })
return expect(new Foo({ field1: null, field2: null })
.validate())
.to.be.rejected
.then(error => {
expect(error.get('xnor')[0].message).to.equal('xnor failed');
return expect(Foo
.build({ field1: 33, field2: null })
return expect(new Foo({ field1: 33, field2: null })
.validate())
.not.to.be.rejected;
});
......@@ -496,7 +493,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
}
}),
foo = Foo.build({ bar: 'a' });
foo = new Foo({ bar: 'a' });
return expect(foo.validate()).not.to.be.rejected.then(() => {
return expect(foo.validate()).not.to.be.rejected;
});
......@@ -515,7 +512,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
const failingBar = Bar.build({ field: 'value3' });
const failingBar = new Bar({ field: 'value3' });
return expect(failingBar.validate()).to.be.rejected.then(errors => {
expect(errors.get('field')).to.have.length(1);
......@@ -536,7 +533,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
const failingBar = Bar.build({ field: 'value3' });
const failingBar = new Bar({ field: 'value3' });
return expect(failingBar.validate({ skip: ['field'] })).not.to.be.rejected;
});
......@@ -554,7 +551,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
const failingBar = Bar.build({ field: this.sequelize.literal('5 + 1') });
const failingBar = new Bar({ field: this.sequelize.literal('5 + 1') });
return expect(failingBar.validate()).not.to.be.rejected;
});
......@@ -590,7 +587,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
const user = User.build({ name: 'RedCat' });
const user = new User({ name: 'RedCat' });
expect(user.getDataValue('name')).to.equal('RedCat');
user.setDataValue('name', 'YellowCat');
......@@ -604,7 +601,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(User.build({
return expect(new User({
email: ['iama', 'dummy.com']
}).validate()).to.be.rejectedWith(Sequelize.ValidationError);
});
......@@ -616,7 +613,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(User.build({
return expect(new User({
email: ['iama', 'dummy.com']
}).validate()).to.be.rejectedWith(Sequelize.ValidationError);
});
......@@ -628,7 +625,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(User.build({
return expect(new User({
email: ['iama', 'dummy.com']
}).validate()).to.be.rejectedWith(Sequelize.ValidationError);
});
......@@ -640,7 +637,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(User.build({
return expect(new User({
email: { lol: true }
}).validate()).to.be.rejectedWith(Sequelize.ValidationError);
});
......@@ -652,7 +649,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(User.build({
return expect(new User({
email: { lol: true }
}).validate()).to.be.rejectedWith(Sequelize.ValidationError);
});
......@@ -664,7 +661,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(User.build({
return expect(new User({
email: { lol: true }
}).validate()).to.be.rejectedWith(Sequelize.ValidationError);
});
......@@ -676,7 +673,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(User.build({
return expect(new User({
email: null
}).validate()).not.to.be.rejected;
});
......@@ -702,13 +699,13 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
return Sequelize.Promise.all([
expect(User.build({
expect(new User({
password: 'short',
salt: '42'
}).validate()).to.be.rejected.then(errors => {
expect(errors.get('password')[0].message).to.equal('Please choose a longer password');
}),
expect(User.build({
expect(new User({
password: 'loooooooong',
salt: '42'
}).validate()).not.to.be.rejected
......@@ -729,10 +726,10 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
return expect(User.build({
return expect(new User({
name: 'abcdefg'
}).validate()).not.to.be.rejected.then(() => {
return expect(User.build({
return expect(new User({
name: 'a'
}).validate()).to.be.rejected;
}).then(errors => {
......
......@@ -152,7 +152,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
return this.sequelize.sync({ force: true })
.then(() => {
return Date.build({ date: Infinity })
return new Date({ date: Infinity })
.save()
.then(date => {
return date.destroy();
......
......@@ -64,7 +64,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
const User = sequelize.define('User', { username: Support.Sequelize.STRING });
return User.sync({ force: true }).then(() => {
return sequelize.transaction().then(t => {
return User.build({ username: 'foo' }).save({ transaction: t }).then(() => {
return new User({ username: 'foo' }).save({ transaction: t }).then(() => {
return User.count().then(count1 => {
return User.count({ transaction: t }).then(count2 => {
expect(count1).to.equal(0);
......@@ -130,7 +130,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('only validates fields in passed array', function() {
return this.User.build({
return new this.User({
validateTest: 'cake', // invalid, but not saved
validateCustom: '1'
}).save({
......@@ -273,7 +273,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
it('stores an entry in the database', function() {
const username = 'user',
User = this.User,
user = this.User.build({
user = new this.User({
username,
touchedAt: new Date(1984, 8, 23)
});
......@@ -327,7 +327,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
const now = new Date();
now.setMilliseconds(0);
const user = this.User.build({ username: 'user' });
const user = new this.User({ username: 'user' });
this.clock.tick(1000);
return user.save().then(savedUser => {
......@@ -520,7 +520,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should fail a validation upon building', function() {
return this.User.build({ aNumber: 0, validateCustom: 'aaaaaaaaaaaaaaaaaaaaaaaaaa' }).save()
return new this.User({ aNumber: 0, validateCustom: 'aaaaaaaaaaaaaaaaaaaaaaaaaa' }).save()
.catch(err => {
expect(err).to.exist;
expect(err).to.be.instanceof(Object);
......@@ -545,7 +545,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('takes zero into account', function() {
return this.User.build({ aNumber: 0 }).save({
return new this.User({ aNumber: 0 }).save({
fields: ['aNumber']
}).then(user => {
expect(user.aNumber).to.equal(0);
......
......@@ -67,9 +67,9 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
});
describe('build', () => {
describe('constructor', () => {
it('returns an object containing all values', function() {
const user = this.User.build({
const user = new this.User({
username: 'Adam',
age: 22,
level: -1,
......@@ -88,7 +88,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('returns a response that can be stringified', function() {
const user = this.User.build({
const user = new this.User({
username: 'test.user',
age: 99,
isAdmin: true,
......@@ -98,7 +98,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('returns a response that can be stringified and then parsed', function() {
const user = this.User.build({ username: 'test.user', age: 99, isAdmin: true });
const user = new this.User({ username: 'test.user', age: 99, isAdmin: true });
expect(JSON.parse(JSON.stringify(user))).to.deep.equal({ username: 'test.user', age: 99, isAdmin: true, isUser: false, id: null });
});
});
......
......@@ -169,7 +169,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should only save passed attributes', function() {
const user = this.User.build();
const user = new this.User();
return user.save().then(() => {
user.set('validateTest', 5);
expect(user.changed('validateTest')).to.be.ok;
......@@ -187,7 +187,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should save attributes affected by setters', function() {
const user = this.User.build();
const user = new this.User();
return user.update({ validateSideEffect: 5 }).then(() => {
expect(user.validateSideEffect).to.be.equal(5);
}).then(() => {
......
......@@ -15,7 +15,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
name: { type: DataTypes.STRING }
});
const user = User.build({ id: 1, name: 'Mick' });
const user = new User({ id: 1, name: 'Mick' });
expect(user.get('id')).to.equal(1);
expect(user.get('name')).to.equal('Mick');
......@@ -32,7 +32,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
identifier: { type: DataTypes.STRING, primaryKey: true }
});
const user = User.build({ identifier: 'identifier' });
const user = new User({ identifier: 'identifier' });
expect(user.get('identifier')).to.equal('identifier');
user.set('identifier', 'another identifier');
......@@ -44,7 +44,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
identifier: { type: DataTypes.STRING, primaryKey: true }
});
const user = User.build({}, {
const user = new User({}, {
isNewRecord: false
});
......@@ -64,7 +64,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
underscored: true
});
const user = User.build({}, {
const user = new User({}, {
isNewRecord: false
});
......@@ -89,7 +89,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
}
});
const user = User.build();
const user = new User();
user.set({
name: 'antonio banderaz',
......@@ -157,7 +157,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
Product.hasMany(Tag);
Product.belongsTo(User);
const product = Product.build({}, {
const product = new Product({}, {
include: [
User,
Tag
......@@ -200,7 +200,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
Product.hasMany(Tag);
Product.belongsTo(User);
const product = Product.build({}, {
const product = new Product({}, {
include: [
User,
Tag
......@@ -241,7 +241,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
}
});
const product = Product.build({
const product = new Product({
price: 10
});
expect(product.get('price')).to.equal(1000);
......@@ -260,7 +260,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
}
});
const product = Product.build({
const product = new Product({
priceInCents: 1000
});
expect(product.get('price')).to.equal(10);
......@@ -282,7 +282,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
}
});
const product = Product.build({
const product = new Product({
price: 10
});
expect(product.toJSON()).to.deep.equal({ withTaxes: 1250, price: 1000, id: null });
......@@ -305,7 +305,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
});
return this.sequelize.sync().then(() => {
const contact = Contact.build({
const contact = new Contact({
first: 'My',
last: 'Name',
tags: ['yes', 'no']
......@@ -330,7 +330,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
Product.belongsTo(User);
const product = Product.build({}, {
const product = new Product({}, {
include: [
User
]
......@@ -357,7 +357,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
title: Sequelize.STRING
});
const product = Product.build({
const product = new Product({
id: 1,
title: 'Chair'
}, { raw: true });
......@@ -401,7 +401,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
Product.belongsTo(User);
const product = Product.build({}, {
const product = new Product({}, {
include: [
User
]
......@@ -455,7 +455,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
name: { type: DataTypes.STRING }
});
const user = User.build({
const user = new User({
name: 'Jan Meier'
});
user.set('name', 'Mick Hansen');
......@@ -469,7 +469,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
});
return User.sync().then(() => {
const user = User.build({
const user = new User({
name: 'Jan Meier'
});
user.set('name', 'Mick Hansen');
......@@ -518,7 +518,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
title: { type: DataTypes.STRING }
});
const user = User.build({
const user = new User({
name: 'Jan Meier',
title: 'Mr'
});
......@@ -534,7 +534,7 @@ describe(Support.getTestDialectTeaser('DAO'), () => {
name: { type: DataTypes.STRING }
});
const user = User.build({
const user = new User({
name: 'Jan Meier'
});
user.set('name', 'Mick Hansen');
......
......@@ -226,7 +226,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
return Task.sync({ force: true }).then(() => {
return Task.build().save().then(record => {
return new Task().save().then(record => {
expect(record.title).to.be.a('string');
expect(record.title).to.equal('');
expect(titleSetter.notCalled).to.be.ok; // The setter method should not be invoked for default values
......@@ -463,9 +463,9 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
});
describe('build', () => {
describe('constructor', () => {
it("doesn't create database entries", function() {
this.User.build({ username: 'John Wayne' });
new this.User({ username: 'John Wayne' });
return this.User.findAll().then(users => {
expect(users).to.have.length(0);
});
......@@ -480,11 +480,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
flag: { type: Sequelize.BOOLEAN, defaultValue: false }
});
expect(Task.build().title).to.equal('a task!');
expect(Task.build().foo).to.equal(2);
expect(Task.build().bar).to.not.be.ok;
expect(Task.build().foobar).to.equal('asd');
expect(Task.build().flag).to.be.false;
expect(new Task().title).to.equal('a task!');
expect(new Task().foo).to.equal(2);
expect(new Task().bar).to.not.be.ok;
expect(new Task().foobar).to.equal('asd');
expect(new Task().flag).to.be.false;
});
it('fills the objects with default values', function() {
......@@ -495,11 +495,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
foobar: { type: Sequelize.TEXT, defaultValue: 'asd' },
flag: { type: Sequelize.BOOLEAN, defaultValue: false }
}, { timestamps: false });
expect(Task.build().title).to.equal('a task!');
expect(Task.build().foo).to.equal(2);
expect(Task.build().bar).to.not.be.ok;
expect(Task.build().foobar).to.equal('asd');
expect(Task.build().flag).to.be.false;
expect(new Task().title).to.equal('a task!');
expect(new Task().foo).to.equal(2);
expect(new Task().bar).to.not.be.ok;
expect(new Task().foobar).to.equal('asd');
expect(new Task().flag).to.be.false;
});
it('attaches getter and setter methods from attribute definition', function() {
......@@ -515,9 +515,9 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
});
expect(Product.build({ price: 42 }).price).to.equal('answer = 84');
expect(new Product({ price: 42 }).price).to.equal('answer = 84');
const p = Product.build({ price: 1 });
const p = new Product({ price: 1 });
expect(p.price).to.equal('answer = 43');
p.price = 0;
......@@ -544,8 +544,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
});
expect(Product.build({ price: 20 }).priceInCents).to.equal(20 * 100);
expect(Product.build({ priceInCents: 30 * 100 }).price).to.equal(`$${30}`);
expect(new Product({ price: 20 }).priceInCents).to.equal(20 * 100);
expect(new Product({ priceInCents: 30 * 100 }).price).to.equal(`$${30}`);
});
it('attaches getter and setter methods from options only if not defined in attribute', function() {
......@@ -567,7 +567,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
});
const p = Product.build({ price1: 1, price2: 2 });
const p = new Product({ price1: 1, price2: 2 });
expect(p.price1).to.equal(10);
expect(p.price2).to.equal(20);
......@@ -589,7 +589,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
Product.hasMany(Tag);
Product.belongsTo(User);
const product = Product.build({
const product = new Product({
id: 1,
title: 'Chair',
Tags: [
......@@ -631,7 +631,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
Product.belongsToMany(User, { as: 'followers', through: 'product_followers' });
User.belongsToMany(Product, { as: 'following', through: 'product_followers' });
const product = Product.build({
const product = new Product({
id: 1,
title: 'Chair',
categories: [
......
......@@ -59,7 +59,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
})
.then(() => {
return Promise.join(
this.Student.build({ no: 1 }).getCourses({ where: { no: 100 } }),
new this.Student({ no: 1 }).getCourses({ where: { no: 100 } }),
this.Score.findOne({ where: { StudentId: 1, CourseId: 100 } })
);
})
......
......@@ -53,7 +53,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
it('should not be ignored in dataValues get', function() {
const user = this.User.build({
const user = new this.User({
field1: 'field1_value',
field2: 'field2_value'
});
......
......@@ -255,20 +255,20 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should be able to insert data into both schemas using instance.save and retrieve/count it', function() {
//building and saving in random order to make sure calling
// .schema doesn't impact model prototype
let restaurauntModel = this.RestaurantOne.build({ bar: 'one.1' });
let restaurauntModel = new this.RestaurantOne({ bar: 'one.1' });
return restaurauntModel.save()
.then(() => {
restaurauntModel = this.RestaurantTwo.build({ bar: 'two.1' });
restaurauntModel = new this.RestaurantTwo({ bar: 'two.1' });
return restaurauntModel.save();
}).then(() => {
restaurauntModel = this.RestaurantOne.build({ bar: 'one.2' });
restaurauntModel = new this.RestaurantOne({ bar: 'one.2' });
return restaurauntModel.save();
}).then(() => {
restaurauntModel = this.RestaurantTwo.build({ bar: 'two.2' });
restaurauntModel = new this.RestaurantTwo({ bar: 'two.2' });
return restaurauntModel.save();
}).then(() => {
restaurauntModel = this.RestaurantTwo.build({ bar: 'two.3' });
restaurauntModel = new this.RestaurantTwo({ bar: 'two.3' });
return restaurauntModel.save();
}).then(() => {
return this.RestaurantOne.findAll();
......@@ -483,12 +483,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should build and persist instances to 2 schemas concurrently in any order', function() {
const Restaurant = this.Restaurant;
let restaurauntModelSchema1 = Restaurant.schema(SCHEMA_ONE).build({ bar: 'one.1' });
const restaurauntModelSchema2 = Restaurant.schema(SCHEMA_TWO).build({ bar: 'two.1' });
let restaurauntModelSchema1 = new (Restaurant.schema(SCHEMA_ONE))({ bar: 'one.1' });
const restaurauntModelSchema2 = new (Restaurant.schema(SCHEMA_TWO))({ bar: 'two.1' });
return restaurauntModelSchema1.save()
.then(() => {
restaurauntModelSchema1 = Restaurant.schema(SCHEMA_ONE).build({ bar: 'one.2' });
restaurauntModelSchema1 = new (Restaurant.schema(SCHEMA_ONE))({ bar: 'one.2' });
return restaurauntModelSchema2.save();
}).then(() => {
return restaurauntModelSchema1.save();
......
......@@ -156,20 +156,20 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should be able to insert data into both schemas using instance.save and retrieve it via findAll', function() {
const Restaurant = this.Restaurant;
let restaurauntModel = Restaurant.build({ bar: 'one.1' });
let restaurauntModel = new Restaurant({ bar: 'one.1' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_ONE })
.then(() => {
restaurauntModel = Restaurant.build({ bar: 'one.2' });
restaurauntModel = new Restaurant({ bar: 'one.2' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_ONE });
}).then(() => {
restaurauntModel = Restaurant.build({ bar: 'two.1' });
restaurauntModel = new Restaurant({ bar: 'two.1' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_TWO });
}).then(() => {
restaurauntModel = Restaurant.build({ bar: 'two.2' });
restaurauntModel = new Restaurant({ bar: 'two.2' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_TWO });
}).then(() => {
restaurauntModel = Restaurant.build({ bar: 'two.3' });
restaurauntModel = new Restaurant({ bar: 'two.3' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_TWO });
}).then(() => {
return Restaurant.findAll({ searchPath: SEARCH_PATH_ONE });
......@@ -210,19 +210,19 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should be able to insert data into both schemas using instance.save count it and retrieve it via findAll with where', function() {
const Restaurant = this.Restaurant;
let restaurauntModel = Restaurant.build({ bar: 'one.1' });
let restaurauntModel = new Restaurant({ bar: 'one.1' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_ONE }).then(() => {
restaurauntModel = Restaurant.build({ bar: 'one.2' });
restaurauntModel = new Restaurant({ bar: 'one.2' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_ONE });
}).then(() => {
restaurauntModel = Restaurant.build({ bar: 'two.1' });
restaurauntModel = new Restaurant({ bar: 'two.1' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_TWO });
}).then(() => {
restaurauntModel = Restaurant.build({ bar: 'two.2' });
restaurauntModel = new Restaurant({ bar: 'two.2' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_TWO });
}).then(() => {
restaurauntModel = Restaurant.build({ bar: 'two.3' });
restaurauntModel = new Restaurant({ bar: 'two.3' });
return restaurauntModel.save({ searchPath: SEARCH_PATH_TWO });
}).then(() => {
return Restaurant.findAll({
......@@ -440,12 +440,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should build and persist instances to 2 schemas concurrently in any order', function() {
const Restaurant = this.Restaurant;
let restaurauntModelSchema1 = Restaurant.build({ bar: 'one.1' });
const restaurauntModelSchema2 = Restaurant.build({ bar: 'two.1' });
let restaurauntModelSchema1 = new Restaurant({ bar: 'one.1' });
const restaurauntModelSchema2 = new Restaurant({ bar: 'two.1' });
return restaurauntModelSchema1.save({ searchPath: SEARCH_PATH_ONE })
.then(() => {
restaurauntModelSchema1 = Restaurant.build({ bar: 'one.2' });
restaurauntModelSchema1 = new Restaurant({ bar: 'one.2' });
return restaurauntModelSchema2.save({ searchPath: SEARCH_PATH_TWO });
}).then(() => {
return restaurauntModelSchema1.save({ searchPath: SEARCH_PATH_ONE });
......
......@@ -765,7 +765,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
'override': overrideGetterMethod
}
};
const testEntity = this.sequelize.define('TestEntity', {}, {
const TestEntity = this.sequelize.define('TestEntity', {}, {
'setterMethods': {
'custom': customSetterMethod,
'override': customOverrideSetterMethod
......@@ -777,7 +777,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
});
// Create Instance to test
const instance = testEntity.build();
const instance = new TestEntity();
// Call Getters
instance.default;
......
......@@ -90,7 +90,7 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => {
User.belongsToMany(Task, { through: 'UserTasks', as: 'task' });
const user = User.build();
const user = new User();
_.each(methods, (alias, method) => {
expect(user[method]()).to.be.a('function');
......@@ -158,13 +158,13 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => {
User.belongsToMany(Task, { through: UserTasks });
Task.belongsToMany(User, { through: UserTasks });
const user =User.build({
const user = new User({
id: 42
}),
task1 = Task.build({
task1 = new Task({
id: 15
}),
task2 = Task.build({
task2 = new Task({
id: 16
});
......
......@@ -45,7 +45,7 @@ describe(Support.getTestDialectTeaser('belongsTo'), () => {
User.belongsTo(Task, { as: 'task' });
const user = User.build();
const user = new User();
_.each(methods, (alias, method) => {
expect(user[method]()).to.be.a('function');
......
......@@ -27,13 +27,13 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
User.hasMany(Task);
const user = User.build({
const user = new User({
id: 42
}),
task1 = Task.build({
task1 = new Task({
id: 15
}),
task2 = Task.build({
task2 = new Task({
id: 16
});
......@@ -118,7 +118,7 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
User.hasMany(Task, { as: 'task' });
const user = User.build();
const user = new User();
_.each(methods, (alias, method) => {
expect(user[method]()).to.be.a('function');
......@@ -130,7 +130,7 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
Project.hasMany(Task);
const company = Project.build();
const company = new Project();
expect(company.hasTasks).not.to.be.a('function');
});
......@@ -146,12 +146,12 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
it('should fetch associations for a single instance', () => {
const findAll = stub(Task, 'findAll').resolves([
Task.build({}),
Task.build({})
new Task({}),
new Task({})
]);
User.Tasks = User.hasMany(Task, { foreignKey });
const actual = User.Tasks.get(User.build({ id: idA }));
const actual = User.Tasks.get(new User({ id: idA }));
const where = {
[foreignKey]: idA
......@@ -171,25 +171,25 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
it('should fetch associations for multiple source instances', () => {
const findAll = stub(Task, 'findAll').returns(
Promise.resolve([
Task.build({
new Task({
'user_id': idA
}),
Task.build({
new Task({
'user_id': idA
}),
Task.build({
new Task({
'user_id': idA
}),
Task.build({
new Task({
'user_id': idB
})
]));
User.Tasks = User.hasMany(Task, { foreignKey });
const actual = User.Tasks.get([
User.build({ id: idA }),
User.build({ id: idB }),
User.build({ id: idC })
new User({ id: idA }),
new User({ id: idB }),
new User({ id: idC })
]);
expect(findAll).to.have.been.calledOnce;
......
......@@ -56,7 +56,7 @@ describe(Support.getTestDialectTeaser('hasOne'), () => {
User.hasOne(Task, { as: 'task' });
const user = User.build();
const user = new User();
_.each(methods, (alias, method) => {
expect(user[method]()).to.be.a('function');
......
......@@ -30,7 +30,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('validate', () => {
it('runs the validation sequence and hooks when the hooks option is true', function() {
const instanceValidator = new InstanceValidator(this.User.build(), { hooks: true });
const instanceValidator = new InstanceValidator(new this.User(), { hooks: true });
const _validate = sinon.spy(instanceValidator, '_validate');
const _validateAndRunHooks = sinon.spy(instanceValidator, '_validateAndRunHooks');
......@@ -41,7 +41,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
it('runs the validation sequence but skips hooks if the hooks option is false', function() {
const instanceValidator = new InstanceValidator(this.User.build(), { hooks: false });
const instanceValidator = new InstanceValidator(new this.User(), { hooks: false });
const _validate = sinon.spy(instanceValidator, '_validate');
const _validateAndRunHooks = sinon.spy(instanceValidator, '_validateAndRunHooks');
......@@ -52,14 +52,14 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
it('fulfills when validation is successful', function() {
const instanceValidator = new InstanceValidator(this.User.build());
const instanceValidator = new InstanceValidator(new this.User());
const result = instanceValidator.validate();
return expect(result).to.be.fulfilled;
});
it('rejects with a validation error when validation fails', function() {
const instanceValidator = new InstanceValidator(this.User.build({ fails: true }));
const instanceValidator = new InstanceValidator(new this.User({ fails: true }));
const result = instanceValidator.validate();
return expect(result).to.be.rejectedWith(SequelizeValidationError);
......@@ -73,7 +73,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
const instanceValidator = new InstanceValidator(User.build());
const instanceValidator = new InstanceValidator(new User());
const result = instanceValidator.validate();
return expect(result).to.be.rejectedWith(SequelizeValidationError, /user\.name cannot be null/);
......@@ -82,7 +82,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('_validateAndRunHooks', () => {
beforeEach(function() {
this.successfulInstanceValidator = new InstanceValidator(this.User.build());
this.successfulInstanceValidator = new InstanceValidator(new this.User());
sinon.stub(this.successfulInstanceValidator, '_validate').resolves();
});
......@@ -99,7 +99,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
it('should run beforeValidate hook but not afterValidate hook when _validate is unsuccessful', function() {
const failingInstanceValidator = new InstanceValidator(this.User.build());
const failingInstanceValidator = new InstanceValidator(new this.User());
sinon.stub(failingInstanceValidator, '_validate').rejects(new Error());
const beforeValidate = sinon.spy();
const afterValidate = sinon.spy();
......@@ -122,7 +122,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('validatedFailed hook', () => {
it('should call validationFailed hook when validation fails', function() {
const failingInstanceValidator = new InstanceValidator(this.User.build());
const failingInstanceValidator = new InstanceValidator(new this.User());
sinon.stub(failingInstanceValidator, '_validate').rejects(new Error());
const validationFailedHook = sinon.spy();
this.User.validationFailed(validationFailedHook);
......@@ -133,7 +133,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
it('should not replace the validation error in validationFailed hook by default', function() {
const failingInstanceValidator = new InstanceValidator(this.User.build());
const failingInstanceValidator = new InstanceValidator(new this.User());
sinon.stub(failingInstanceValidator, '_validate').rejects(new SequelizeValidationError());
const validationFailedHook = sinon.stub().resolves();
this.User.validationFailed(validationFailedHook);
......@@ -144,7 +144,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
it('should replace the validation error if validationFailed hook creates a new error', function() {
const failingInstanceValidator = new InstanceValidator(this.User.build());
const failingInstanceValidator = new InstanceValidator(new this.User());
sinon.stub(failingInstanceValidator, '_validate').rejects(new SequelizeValidationError());
const validationFailedHook = sinon.stub().throws(new Error('validation failed hook error'));
this.User.validationFailed(validationFailedHook);
......
......@@ -37,7 +37,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
}, {
timestamp: false
}),
instance = Model.build({ ip: '127.0.0.1', ip2: '0.0.0.0' });
instance = new Model({ ip: '127.0.0.1', ip2: '0.0.0.0' });
expect(instance.get('created_time')).to.be.ok;
expect(instance.get('created_time')).to.be.an.instanceof(Date);
......@@ -57,7 +57,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
defaultValue: DataTypes.UUIDV4
}
}),
instance = Model.build({
instance = new Model({
id: undefined
});
......@@ -76,7 +76,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
defaultValue: 2
}
}),
instance = Model.build({
instance = new Model({
number1: undefined
});
......@@ -93,11 +93,11 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
defaultValue: { foo: 'bar' }
}
}),
instance = Model.build();
instance = new Model();
instance.data.foo = 'biz';
expect(instance.get('data')).to.eql({ foo: 'biz' });
expect(Model.build().get('data')).to.eql({ foo: 'bar' });
expect(new Model().get('data')).to.eql({ foo: 'bar' });
});
});
});
......@@ -18,7 +18,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should return true for changed primitive', function() {
const user = this.User.build({
const user = new this.User({
name: 'a'
}, {
isNewRecord: false,
......@@ -33,7 +33,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should return falsy for unchanged primitive', function() {
const user = this.User.build({
const user = new this.User({
name: 'a',
meta: null
}, {
......@@ -48,7 +48,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should return true for multiple changed values', function() {
const user = this.User.build({
const user = new this.User({
name: 'a',
birthday: new Date(new Date() - 10)
}, {
......@@ -67,7 +67,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
const firstDate = new Date(milliseconds);
const secondDate = new Date(milliseconds);
const user = this.User.build({
const user = new this.User({
birthday: firstDate
}, {
isNewRecord: false,
......@@ -79,7 +79,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should return true for changed JSON with same object', function() {
const user = this.User.build({
const user = new this.User({
meta: {
city: 'Copenhagen'
}
......@@ -96,7 +96,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should return true for JSON dot.separated key with changed values', function() {
const user = this.User.build({
const user = new this.User({
meta: {
city: 'Stockholm'
}
......@@ -110,7 +110,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should return false for JSON dot.separated key with same value', function() {
const user = this.User.build({
const user = new this.User({
meta: {
city: 'Gothenburg'
}
......@@ -124,7 +124,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should return true for JSON dot.separated key with object', function() {
const user = this.User.build({
const user = new this.User({
meta: {
address: { street: 'Main street', number: '40' }
}
......@@ -138,7 +138,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should return false for JSON dot.separated key with same object', function() {
const user = this.User.build({
const user = new this.User({
meta: {
address: { street: 'Main street', number: '40' }
}
......@@ -157,7 +157,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
attributes[attr] = null;
}
const user = this.User.build(attributes, {
const user = new this.User(attributes, {
isNewRecord: false,
raw: true
});
......@@ -173,7 +173,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
describe('setDataValue', () => {
it('should return falsy for unchanged primitive', function() {
const user = this.User.build({
const user = new this.User({
name: 'a',
meta: null
}, {
......
......@@ -33,7 +33,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should allow decrements even if options are not given', () => {
instance = Model.build({ id: 3 }, { isNewRecord: false });
instance = new Model({ id: 3 }, { isNewRecord: false });
expect(() => {
instance.decrement(['id']);
}).to.not.throw();
......
......@@ -33,7 +33,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should allow destroies even if options are not given', () => {
instance = Model.build({ id: 1 }, { isNewRecord: false });
instance = new Model({ id: 1 }, { isNewRecord: false });
expect(() => {
instance.destroy();
}).to.not.throw();
......
......@@ -20,13 +20,13 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('invokes getter if raw: false', function() {
this.User.build().get('name');
new this.User().get('name');
expect(this.getSpy).to.have.been.called;
});
it('does not invoke getter if raw: true', function() {
this.User.build().get('name', { raw: true });
new this.User().get('name', { raw: true });
expect(this.getSpy).not.to.have.been.called;
});
......
......@@ -33,7 +33,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should allow increments even if options are not given', () => {
instance = Model.build({ id: 1 }, { isNewRecord: false });
instance = new Model({ id: 1 }, { isNewRecord: false });
expect(() => {
instance.increment(['id']);
}).to.not.throw();
......
......@@ -31,14 +31,14 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
paranoid: true
});
this.paranoidUser = ParanoidUser.build({
this.paranoidUser = new ParanoidUser({
name: 'a'
}, {
isNewRecord: false,
raw: true
});
this.user = User.build({
this.user = new User({
name: 'a'
}, {
isNewRecord: false,
......
......@@ -22,7 +22,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
}
});
const instance = Model.build({ text: 'a', textCustom: 'abc' });
const instance = new Model({ text: 'a', textCustom: 'abc' });
expect(instance.previous('text')).to.be.not.ok;
expect(instance.previous('textCustom')).to.be.not.ok;
......
......@@ -38,7 +38,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should allow reloads even if options are not given', () => {
instance = Model.build({ id: 1 }, { isNewRecord: false });
instance = new Model({ id: 1 }, { isNewRecord: false });
expect(() => {
instance.reload();
}).to.not.throw();
......
......@@ -38,7 +38,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should allow restores even if options are not given', () => {
instance = Model.build({ id: 1 }, { isNewRecord: false });
instance = new Model({ id: 1 }, { isNewRecord: false });
expect(() => {
instance.restore();
}).to.not.throw();
......
......@@ -13,7 +13,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
const Model = current.define('User', {
}),
instance = Model.build({}, { isNewRecord: false });
instance = new Model({}, { isNewRecord: false });
expect(() => {
instance.save();
......@@ -44,7 +44,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('should allow saves even if options are not given', () => {
instance = Model.build({});
instance = new Model({});
expect(() => {
instance.save();
}).to.not.throw();
......
......@@ -15,9 +15,9 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
const User = current.define('User', {
meta: DataTypes.JSONB
});
const user = User.build({
const user = new User({
meta: {
location: 'Stockhollm'
location: 'Stockholm'
}
}, {
isNewRecord: false,
......@@ -41,9 +41,9 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
defaultValue: {}
}
});
const user1 = User.build({});
user1.set('meta.location', 'Stockhollm');
const user2 = User.build({});
const user1 = new User({});
user1.set('meta.location', 'Stockholm');
const user2 = new User({});
expect(user2.get('meta')).to.deep.equal({});
});
......@@ -54,7 +54,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
allowNull: true
}
});
const user1 = User.build({
const user1 = new User({
date: null
});
user1.set('date', '1970-01-01');
......@@ -66,7 +66,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
const User = current.define('User', {
date: DataTypes.DATE
});
const user = User.build({
const user = new User({
date: ' '
}, {
isNewRecord: false,
......@@ -106,7 +106,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('does not set field to changed if field is set to the same value with custom setter using primitive value', () => {
const user = User.build({
const user = new User({
phoneNumber: '+1 234 567'
});
return user.save().then(() => {
......@@ -118,7 +118,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('sets field to changed if field is set to the another value with custom setter using primitive value', () => {
const user = User.build({
const user = new User({
phoneNumber: '+1 234 567'
});
return user.save().then(() => {
......@@ -130,7 +130,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('does not set field to changed if field is set to the same value with custom setter using object', () => {
const user = User.build({
const user = new User({
phoneNumber: '+1 234 567'
});
return user.save().then(() => {
......@@ -142,7 +142,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
});
it('sets field to changed if field is set to the another value with custom setter using object', () => {
const user = User.build({
const user = new User({
phoneNumber: '+1 234 567'
});
return user.save().then(() => {
......
......@@ -12,7 +12,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
const User = current.define('User', {
name: DataTypes.STRING
});
const user = User.build({ name: 'my-name' });
const user = new User({ name: 'my-name' });
const json1 = user.toJSON();
expect(json1).to.have.property('name').and.be.equal('my-name');
......@@ -28,7 +28,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
name: DataTypes.STRING,
permissions: DataTypes.JSON
});
const user = User.build({ name: 'my-name', permissions: { admin: true, special: 'foobar' } });
const user = new User({ name: 'my-name', permissions: { admin: true, special: 'foobar' } });
const json = user.toJSON();
expect(json)
......
......@@ -45,7 +45,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}, { timestamps: false });
before(function() {
this.stub = sinon.stub(current.getQueryInterface(), 'select').callsFake(() => Model.build({}));
this.stub = sinon.stub(current.getQueryInterface(), 'select').callsFake(() => new Model({}));
this.warnOnInvalidOptionsStub = sinon.stub(Model, 'warnOnInvalidOptions');
});
......
......@@ -13,7 +13,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
set: DataTypes.STRING
});
const user = User.build({ set: 'A' });
const user = new User({ set: 'A' });
expect(user.get('set')).to.equal('A');
user.set('set', 'B');
expect(user.get('set')).to.equal('B');
......
......@@ -30,7 +30,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
Model.removeAttribute('id');
const instance = Model.build();
const instance = new Model();
expect(instance.dataValues).not.to.include.keys('undefined');
});
});
......
......@@ -196,7 +196,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
const failingUser = UserFail.build({ name: failingValue });
const failingUser = new UserFail({ name: failingValue });
return expect(failingUser.validate()).to.be.rejected.then(_errors => {
expect(_errors.get('name')[0].message).to.equal(message);
......@@ -227,7 +227,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
validate: validations
}
});
const successfulUser = UserSuccess.build({ name: succeedingValue });
const successfulUser = new UserSuccess({ name: succeedingValue });
return expect(successfulUser.validate()).not.to.be.rejected;
});
};
......@@ -273,7 +273,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
before(function() {
this.stub = sinon.stub(current, 'query').callsFake(() => new Promise.resolve([User.build({}), 1]));
this.stub = sinon.stub(current, 'query').callsFake(() => new Promise.resolve([new User({}), 1]));
});
after(function() {
......@@ -480,7 +480,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
before(function() {
this.stub = sinon.stub(current, 'query').resolves([User.build(), 1]);
this.stub = sinon.stub(current, 'query').resolves([new User(), 1]);
});
after(function() {
......@@ -555,7 +555,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
});
before(function() {
this.stub = sinon.stub(current, 'query').resolves([User.build(), 1]);
this.stub = sinon.stub(current, 'query').resolves([new User(), 1]);
});
after(function() {
......@@ -624,7 +624,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
this.stub = sinon.stub(current, 'query').resolves([this.User.build(), 1]);
this.stub = sinon.stub(current, 'query').resolves([new this.User(), 1]);
});
after(function() {
......@@ -693,7 +693,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}
});
this.stub = sinon.stub(current, 'query').resolves([this.User.build(), 1]);
this.stub = sinon.stub(current, 'query').resolves([new this.User(), 1]);
});
after(function() {
......
......@@ -601,7 +601,7 @@ export interface CountWithOptions extends CountOptions {
export interface FindAndCountOptions extends CountOptions, FindOptions {}
/**
* Options for Model.build method
* Options for Model constructor
*/
export interface BuildOptions {
/**
......@@ -1872,16 +1872,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
): Promise<number>;
/**
* Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
*/
public static build<M extends Model>(
this: { new (): M } & typeof Model,
record?: object,
options?: BuildOptions
): M;
/**
* Undocumented bulkBuild
* Builds multiple model instances in one go.
*/
public static bulkBuild<M extends Model>(
this: { new (): M } & typeof Model,
......@@ -2540,7 +2531,7 @@ export abstract class Model<T = any, T2 = any> extends Hooks {
*
* Set can also be used to build instances for associations, if you have values for those.
* When using set with associations you need to make sure the property key matches the alias of the
* association while also making sure that the proper include options have been set (from .build() or
* association while also making sure that the proper include options have been set (from the constructor or
* .findOne())
*
* If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!