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

Commit 777fbd3b by Simon Schick Committed by GitHub

refactor: replace lodash defaults with object spread (#12215)

1 parent ce5b4ef9
...@@ -284,8 +284,8 @@ class BelongsToMany extends Association { ...@@ -284,8 +284,8 @@ class BelongsToMany extends Association {
const targetKey = this.target.rawAttributes[this.targetKey]; const targetKey = this.target.rawAttributes[this.targetKey];
const targetKeyType = targetKey.type; const targetKeyType = targetKey.type;
const targetKeyField = this.targetKeyField; const targetKeyField = this.targetKeyField;
const sourceAttribute = _.defaults({}, this.foreignKeyAttribute, { type: sourceKeyType }); const sourceAttribute = { type: sourceKeyType, ...this.foreignKeyAttribute };
const targetAttribute = _.defaults({}, this.otherKeyAttribute, { type: targetKeyType }); const targetAttribute = { type: targetKeyType, ...this.otherKeyAttribute };
if (this.primaryKeyDeleted === true) { if (this.primaryKeyDeleted === true) {
targetAttribute.primaryKey = sourceAttribute.primaryKey = true; targetAttribute.primaryKey = sourceAttribute.primaryKey = true;
...@@ -594,7 +594,7 @@ class BelongsToMany extends Association { ...@@ -594,7 +594,7 @@ class BelongsToMany extends Association {
throughAttributes = {}; throughAttributes = {};
} }
const attributes = _.defaults({}, throughAttributes, defaultAttributes); const attributes = { ...defaultAttributes, ...throughAttributes };
if (Object.keys(attributes).length) { if (Object.keys(attributes).length) {
promises.push( promises.push(
...@@ -612,28 +612,26 @@ class BelongsToMany extends Association { ...@@ -612,28 +612,26 @@ class BelongsToMany extends Association {
if (obsoleteAssociations.length > 0) { if (obsoleteAssociations.length > 0) {
promises.push( promises.push(
this.through.model.destroy(_.defaults({ this.through.model.destroy({
...options,
where: { where: {
[identifier]: sourceInstance.get(sourceKey), [identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: obsoleteAssociations.map(obsoleteAssociation => obsoleteAssociation[foreignIdentifier]), [foreignIdentifier]: obsoleteAssociations.map(obsoleteAssociation => obsoleteAssociation[foreignIdentifier]),
...this.through.scope ...this.through.scope
} }
}, options)) })
); );
} }
if (unassociatedObjects.length > 0) { if (unassociatedObjects.length > 0) {
const bulk = unassociatedObjects.map(unassociatedObject => { const bulk = unassociatedObjects.map(unassociatedObject => {
let attributes = {}; return {
...defaultAttributes,
attributes[identifier] = sourceInstance.get(sourceKey); ...unassociatedObject[this.through.model.name],
attributes[foreignIdentifier] = unassociatedObject.get(targetKey); [identifier]: sourceInstance.get(sourceKey),
[foreignIdentifier]: unassociatedObject.get(targetKey),
attributes = _.defaults(attributes, unassociatedObject[this.through.model.name], defaultAttributes); ...this.through.scope
};
Object.assign(attributes, this.through.scope);
return attributes;
}); });
promises.push(this.through.model.bulkCreate(bulk, { validate: true, ...options })); promises.push(this.through.model.bulkCreate(bulk, { validate: true, ...options }));
...@@ -643,7 +641,7 @@ class BelongsToMany extends Association { ...@@ -643,7 +641,7 @@ class BelongsToMany extends Association {
}; };
try { try {
const currentRows = await this.through.model.findAll(_.defaults({ where, raw: true }, options)); const currentRows = await this.through.model.findAll({ ...options, where, raw: true });
return await updateAssociations(currentRows); return await updateAssociations(currentRows);
} catch (error) { } catch (error) {
if (error instanceof EmptyResultError) return updateAssociations([]); if (error instanceof EmptyResultError) return updateAssociations([]);
...@@ -695,7 +693,7 @@ class BelongsToMany extends Association { ...@@ -695,7 +693,7 @@ class BelongsToMany extends Association {
unassociatedObjects.push(obj); unassociatedObjects.push(obj);
} else { } else {
const throughAttributes = obj[association.through.model.name]; const throughAttributes = obj[association.through.model.name];
const attributes = _.defaults({}, throughAttributes, defaultAttributes); const attributes = { ...defaultAttributes, ...throughAttributes };
if (Object.keys(attributes).some(attribute => attributes[attribute] !== existingAssociation[attribute])) { if (Object.keys(attributes).some(attribute => attributes[attribute] !== existingAssociation[attribute])) {
changedAssociations.push(obj); changedAssociations.push(obj);
...@@ -706,7 +704,7 @@ class BelongsToMany extends Association { ...@@ -706,7 +704,7 @@ class BelongsToMany extends Association {
if (unassociatedObjects.length > 0) { if (unassociatedObjects.length > 0) {
const bulk = unassociatedObjects.map(unassociatedObject => { const bulk = unassociatedObjects.map(unassociatedObject => {
const throughAttributes = unassociatedObject[association.through.model.name]; const throughAttributes = unassociatedObject[association.through.model.name];
const attributes = _.defaults({}, throughAttributes, defaultAttributes); const attributes = { ...defaultAttributes, ...throughAttributes };
attributes[identifier] = sourceInstance.get(sourceKey); attributes[identifier] = sourceInstance.get(sourceKey);
attributes[foreignIdentifier] = unassociatedObject.get(targetKey); attributes[foreignIdentifier] = unassociatedObject.get(targetKey);
...@@ -721,7 +719,7 @@ class BelongsToMany extends Association { ...@@ -721,7 +719,7 @@ class BelongsToMany extends Association {
for (const assoc of changedAssociations) { for (const assoc of changedAssociations) {
let throughAttributes = assoc[association.through.model.name]; let throughAttributes = assoc[association.through.model.name];
const attributes = _.defaults({}, throughAttributes, defaultAttributes); const attributes = { ...defaultAttributes, ...throughAttributes };
// Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute object) // Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute object)
if (throughAttributes instanceof association.through.model) { if (throughAttributes instanceof association.through.model) {
throughAttributes = {}; throughAttributes = {};
...@@ -737,7 +735,7 @@ class BelongsToMany extends Association { ...@@ -737,7 +735,7 @@ class BelongsToMany extends Association {
}; };
try { try {
const currentRows = await association.through.model.findAll(_.defaults({ where, raw: true }, options)); const currentRows = await association.through.model.findAll({ ...options, where, raw: true });
const [associations] = await updateAssociations(currentRows); const [associations] = await updateAssociations(currentRows);
return associations; return associations;
} catch (error) { } catch (error) {
...@@ -767,7 +765,7 @@ class BelongsToMany extends Association { ...@@ -767,7 +765,7 @@ class BelongsToMany extends Association {
[association.foreignIdentifier]: oldAssociatedObjects.map(newInstance => newInstance.get(association.targetKey)) [association.foreignIdentifier]: oldAssociatedObjects.map(newInstance => newInstance.get(association.targetKey))
}; };
return association.through.model.destroy(_.defaults({ where }, options)); return association.through.model.destroy({ ...options, where });
} }
/** /**
......
...@@ -79,12 +79,13 @@ class BelongsTo extends Association { ...@@ -79,12 +79,13 @@ class BelongsTo extends Association {
// the id is in the source table // the id is in the source table
_injectAttributes() { _injectAttributes() {
const newAttributes = {}; const newAttributes = {
[this.foreignKey]: {
newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, { type: this.options.keyType || this.target.rawAttributes[this.targetKey].type,
type: this.options.keyType || this.target.rawAttributes[this.targetKey].type, allowNull: true,
allowNull: true ...this.foreignKeyAttribute
}); }
};
if (this.options.constraints !== false) { if (this.options.constraints !== false) {
const source = this.source.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey]; const source = this.source.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];
......
...@@ -112,15 +112,17 @@ class HasMany extends Association { ...@@ -112,15 +112,17 @@ class HasMany extends Association {
// the id is in the target table // the id is in the target table
// or in an extra table which connects two tables // or in an extra table which connects two tables
_injectAttributes() { _injectAttributes() {
const newAttributes = {}; const newAttributes = {
[this.foreignKey]: {
type: this.options.keyType || this.source.rawAttributes[this.sourceKeyAttribute].type,
allowNull: true,
...this.foreignKeyAttribute
}
};
// Create a new options object for use with addForeignKeyConstraints, to avoid polluting this.options in case it is later used for a n:m // Create a new options object for use with addForeignKeyConstraints, to avoid polluting this.options in case it is later used for a n:m
const constraintOptions = { ...this.options }; const constraintOptions = { ...this.options };
newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, {
type: this.options.keyType || this.source.rawAttributes[this.sourceKeyAttribute].type,
allowNull: true
});
if (this.options.constraints !== false) { if (this.options.constraints !== false) {
const target = this.target.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey]; const target = this.target.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];
constraintOptions.onDelete = constraintOptions.onDelete || (target.allowNull ? 'SET NULL' : 'CASCADE'); constraintOptions.onDelete = constraintOptions.onDelete || (target.allowNull ? 'SET NULL' : 'CASCADE');
...@@ -329,7 +331,7 @@ class HasMany extends Association { ...@@ -329,7 +331,7 @@ class HasMany extends Association {
targetInstances = this.toInstanceArray(targetInstances); targetInstances = this.toInstanceArray(targetInstances);
} }
const oldAssociations = await this.get(sourceInstance, _.defaults({ scope: false, raw: true }, options)); const oldAssociations = await this.get(sourceInstance, { ...options, scope: false, raw: true });
const promises = []; const promises = [];
const obsoleteAssociations = oldAssociations.filter(old => const obsoleteAssociations = oldAssociations.filter(old =>
!targetInstances.find(obj => !targetInstances.find(obj =>
...@@ -357,9 +359,10 @@ class HasMany extends Association { ...@@ -357,9 +359,10 @@ class HasMany extends Association {
promises.push(this.target.unscoped().update( promises.push(this.target.unscoped().update(
update, update,
_.defaults({ {
...options,
where: updateWhere where: updateWhere
}, options) }
)); ));
} }
...@@ -376,9 +379,10 @@ class HasMany extends Association { ...@@ -376,9 +379,10 @@ class HasMany extends Association {
promises.push(this.target.unscoped().update( promises.push(this.target.unscoped().update(
update, update,
_.defaults({ {
...options,
where: updateWhere where: updateWhere
}, options) }
)); ));
} }
...@@ -414,7 +418,7 @@ class HasMany extends Association { ...@@ -414,7 +418,7 @@ class HasMany extends Association {
) )
}; };
await this.target.unscoped().update(update, _.defaults({ where }, options)); await this.target.unscoped().update(update, { ...options, where });
return sourceInstance; return sourceInstance;
} }
...@@ -442,7 +446,7 @@ class HasMany extends Association { ...@@ -442,7 +446,7 @@ class HasMany extends Association {
) )
}; };
await this.target.unscoped().update(update, _.defaults({ where }, options)); await this.target.unscoped().update(update, { ...options, where });
return this; return this;
} }
......
...@@ -78,12 +78,13 @@ class HasOne extends Association { ...@@ -78,12 +78,13 @@ class HasOne extends Association {
// the id is in the target table // the id is in the target table
_injectAttributes() { _injectAttributes() {
const newAttributes = {}; const newAttributes = {
[this.foreignKey]: {
newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, { type: this.options.keyType || this.source.rawAttributes[this.sourceKey].type,
type: this.options.keyType || this.source.rawAttributes[this.sourceKey].type, allowNull: true,
allowNull: true ...this.foreignKeyAttribute
}); }
};
if (this.options.constraints !== false) { if (this.options.constraints !== false) {
const target = this.target.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey]; const target = this.target.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];
......
...@@ -401,7 +401,7 @@ class QueryGenerator { ...@@ -401,7 +401,7 @@ class QueryGenerator {
} }
} }
const whereOptions = _.defaults({ bindParam }, options); const whereOptions = { ...options, bindParam };
if (values.length === 0) { if (values.length === 0) {
return ''; return '';
......
...@@ -344,7 +344,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -344,7 +344,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
upsertQuery(tableName, insertValues, updateValues, where, model, options) { upsertQuery(tableName, insertValues, updateValues, where, model, options) {
const primaryField = this.quoteIdentifier(model.primaryKeyField); const primaryField = this.quoteIdentifier(model.primaryKeyField);
const upsertOptions = _.defaults({ bindParam: false, returning: ['*'] }, options); const upsertOptions = { ...options, bindParam: false, returning: ['*'] };
const insert = this.insertQuery(tableName, insertValues, model.rawAttributes, upsertOptions); const insert = this.insertQuery(tableName, insertValues, model.rawAttributes, upsertOptions);
const update = this.updateQuery(tableName, updateValues, where, upsertOptions, model.rawAttributes); const update = this.updateQuery(tableName, updateValues, where, upsertOptions, model.rawAttributes);
const returningRegex = /RETURNING \*(?![\s\S]*RETURNING \*)/; const returningRegex = /RETURNING \*(?![\s\S]*RETURNING \*)/;
......
...@@ -181,7 +181,7 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator { ...@@ -181,7 +181,7 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
const bind = []; const bind = [];
const bindParam = this.bindParam(bind); const bindParam = this.bindParam(bind);
const upsertOptions = _.defaults({ bindParam }, options); const upsertOptions = { ...options, bindParam };
const insert = this.insertQuery(tableName, insertValues, model.rawAttributes, upsertOptions); const insert = this.insertQuery(tableName, insertValues, model.rawAttributes, upsertOptions);
const update = this.updateQuery(tableName, updateValues, where, upsertOptions, model.rawAttributes); const update = this.updateQuery(tableName, updateValues, where, upsertOptions, model.rawAttributes);
...@@ -221,7 +221,7 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator { ...@@ -221,7 +221,7 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
} }
let query; let query;
const whereOptions = _.defaults({ bindParam }, options); const whereOptions = { ...options, bindParam };
if (options.limit) { if (options.limit) {
query = `UPDATE ${this.quoteTable(tableName)} SET ${values.join(',')} WHERE rowid IN (SELECT rowid FROM ${this.quoteTable(tableName)} ${this.whereQuery(where, whereOptions)} LIMIT ${this.escape(options.limit)})`; query = `UPDATE ${this.quoteTable(tableName)} SET ${values.join(',')} WHERE rowid IN (SELECT rowid FROM ${this.quoteTable(tableName)} ${this.whereQuery(where, whereOptions)} LIMIT ${this.escape(options.limit)})`;
......
...@@ -18,17 +18,19 @@ const { promisify } = require('util'); ...@@ -18,17 +18,19 @@ const { promisify } = require('util');
*/ */
class InstanceValidator { class InstanceValidator {
constructor(modelInstance, options) { constructor(modelInstance, options) {
options = { ...options }; options = {
// assign defined and default options
hooks: true,
...options
};
if (options.fields && !options.skip) { if (options.fields && !options.skip) {
options.skip = _.difference(Object.keys(modelInstance.constructor.rawAttributes), options.fields); options.skip = _.difference(Object.keys(modelInstance.constructor.rawAttributes), options.fields);
} else {
options.skip = options.skip || [];
} }
// assign defined and default options this.options = options;
this.options = _.defaults(options, {
skip: [],
hooks: true
});
this.modelInstance = modelInstance; this.modelInstance = modelInstance;
......
...@@ -3367,11 +3367,11 @@ class Model { ...@@ -3367,11 +3367,11 @@ class Model {
* @returns {Promise<Model[],?number>} returns an array of affected rows and affected count with `options.returning` true, whenever supported by dialect * @returns {Promise<Model[],?number>} returns an array of affected rows and affected count with `options.returning` true, whenever supported by dialect
*/ */
static async decrement(fields, options) { static async decrement(fields, options) {
options = _.defaults({ increment: false }, options, { return this.increment(fields, {
by: 1 by: 1,
...options,
increment: false
}); });
return await this.increment(fields, options);
} }
static _optionsMustContainWhere(options) { static _optionsMustContainWhere(options) {
...@@ -4086,7 +4086,7 @@ class Model { ...@@ -4086,7 +4086,7 @@ class Model {
* @returns {Promise} * @returns {Promise}
*/ */
async validate(options) { async validate(options) {
return await new InstanceValidator(this, options).validate(); return new InstanceValidator(this, options).validate();
} }
/** /**
...@@ -4167,7 +4167,7 @@ class Model { ...@@ -4167,7 +4167,7 @@ class Model {
this.setDataValue(attributeName, new Date()); this.setDataValue(attributeName, new Date());
} }
result = await this.save(_.defaults({ hooks: false }, options)); result = await this.save({ ...options, hooks: false });
} else { } else {
result = await this.constructor.QueryInterface.delete(this, this.constructor.getTableName(options), where, { type: QueryTypes.DELETE, limit: null, ...options }); result = await this.constructor.QueryInterface.delete(this, this.constructor.getTableName(options), where, { type: QueryTypes.DELETE, limit: null, ...options });
} }
...@@ -4307,11 +4307,11 @@ class Model { ...@@ -4307,11 +4307,11 @@ class Model {
* @returns {Promise} * @returns {Promise}
*/ */
async decrement(fields, options) { async decrement(fields, options) {
options = _.defaults({ increment: false }, options, { return this.increment(fields, {
by: 1 by: 1,
...options,
increment: false
}); });
return await this.increment(fields, options);
} }
/** /**
......
...@@ -751,9 +751,12 @@ class Sequelize { ...@@ -751,9 +751,12 @@ class Sequelize {
* @returns {Promise} * @returns {Promise}
*/ */
async sync(options) { async sync(options) {
options = { ...options }; options = {
options.hooks = options.hooks === undefined ? true : !!options.hooks; ...this.options,
options = _.defaults(options, this.options.sync, this.options); ...this.options.sync,
...options,
hooks: options ? options.hooks !== false : true
};
if (options.match) { if (options.match) {
if (!options.match.test(this.config.database)) { if (!options.match.test(this.config.database)) {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!