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

Commit ce5b4ef9 by Simon Schick Committed by GitHub

refactor: replace lodash clone with object spread (#12214)

1 parent 6640ba2a
...@@ -423,7 +423,7 @@ class BelongsToMany extends Association { ...@@ -423,7 +423,7 @@ class BelongsToMany extends Association {
let throughWhere; let throughWhere;
if (this.scope) { if (this.scope) {
scopeWhere = _.clone(this.scope); scopeWhere = { ...this.scope };
} }
options.where = { options.where = {
...@@ -667,7 +667,7 @@ class BelongsToMany extends Association { ...@@ -667,7 +667,7 @@ class BelongsToMany extends Association {
// If newInstances is null or undefined, no-op // If newInstances is null or undefined, no-op
if (!newInstances) return Promise.resolve(); if (!newInstances) return Promise.resolve();
options = _.clone(options) || {}; options = { ...options };
const association = this; const association = this;
const sourceKey = association.sourceKey; const sourceKey = association.sourceKey;
......
...@@ -114,7 +114,7 @@ class HasMany extends Association { ...@@ -114,7 +114,7 @@ class HasMany extends Association {
_injectAttributes() { _injectAttributes() {
const newAttributes = {}; const newAttributes = {};
// 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 = _.clone(this.options); const constraintOptions = { ...this.options };
newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, { newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, {
type: this.options.keyType || this.source.rawAttributes[this.sourceKeyAttribute].type, type: this.options.keyType || this.source.rawAttributes[this.sourceKeyAttribute].type,
......
...@@ -2,8 +2,6 @@ ...@@ -2,8 +2,6 @@
const DataTypes = require('../../data-types'); const DataTypes = require('../../data-types');
const QueryTypes = require('../../query-types'); const QueryTypes = require('../../query-types');
const _ = require('lodash');
/** /**
Returns an object that handles Postgres special needs to do certain queries. Returns an object that handles Postgres special needs to do certain queries.
...@@ -55,9 +53,11 @@ async function ensureEnums(qi, tableName, attributes, options, model) { ...@@ -55,9 +53,11 @@ async function ensureEnums(qi, tableName, attributes, options, model) {
// This little function allows us to re-use the same code that prepends or appends new value to enum array // This little function allows us to re-use the same code that prepends or appends new value to enum array
const addEnumValue = (field, value, relativeValue, position = 'before', spliceStart = promises.length) => { const addEnumValue = (field, value, relativeValue, position = 'before', spliceStart = promises.length) => {
const valueOptions = _.clone(options); const valueOptions = {
valueOptions.before = null; ...options,
valueOptions.after = null; before: null,
after: null
};
switch (position) { switch (position) {
case 'after': case 'after':
......
'use strict'; 'use strict';
const _ = require('lodash');
const sequelizeErrors = require('../../errors'); const sequelizeErrors = require('../../errors');
const QueryTypes = require('../../query-types'); const QueryTypes = require('../../query-types');
...@@ -86,7 +85,7 @@ async function renameColumn(qi, tableName, attrNameBefore, attrNameAfter, option ...@@ -86,7 +85,7 @@ async function renameColumn(qi, tableName, attrNameBefore, attrNameAfter, option
options = options || {}; options = options || {};
const fields = await qi.describeTable(tableName, options); const fields = await qi.describeTable(tableName, options);
fields[attrNameAfter] = _.clone(fields[attrNameBefore]); fields[attrNameAfter] = { ...fields[attrNameBefore] };
delete fields[attrNameBefore]; delete fields[attrNameBefore];
const sql = qi.QueryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields); const sql = qi.QueryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields);
......
...@@ -18,7 +18,7 @@ const { promisify } = require('util'); ...@@ -18,7 +18,7 @@ const { promisify } = require('util');
*/ */
class InstanceValidator { class InstanceValidator {
constructor(modelInstance, options) { constructor(modelInstance, options) {
options = _.clone(options) || {}; options = { ...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);
...@@ -405,7 +405,7 @@ class InstanceValidator { ...@@ -405,7 +405,7 @@ class InstanceValidator {
} }
/** /**
* The error key for arguments as passed by custom validators * The error key for arguments as passed by custom validators
* *
* @type {string} * @type {string}
* @private * @private
*/ */
......
...@@ -123,7 +123,7 @@ class Model { ...@@ -123,7 +123,7 @@ class Model {
let defaults; let defaults;
let key; let key;
values = values && _.clone(values) || {}; values = { ...values };
if (options.isNewRecord) { if (options.isNewRecord) {
defaults = {}; defaults = {};
...@@ -272,23 +272,18 @@ class Model { ...@@ -272,23 +272,18 @@ class Model {
}; };
} }
const existingAttributes = _.clone(this.rawAttributes); const newRawAttributes = {
this.rawAttributes = {}; ...head,
...this.rawAttributes
_.each(head, (value, attr) => { };
this.rawAttributes[attr] = value;
});
_.each(existingAttributes, (value, attr) => {
this.rawAttributes[attr] = value;
});
_.each(tail, (value, attr) => { _.each(tail, (value, attr) => {
if (this.rawAttributes[attr] === undefined) { if (newRawAttributes[attr] === undefined) {
this.rawAttributes[attr] = value; newRawAttributes[attr] = value;
} }
}); });
this.rawAttributes = newRawAttributes;
if (!Object.keys(this.primaryKeys).length) { if (!Object.keys(this.primaryKeys).length) {
this.primaryKeys.id = this.rawAttributes.id; this.primaryKeys.id = this.rawAttributes.id;
} }
...@@ -1070,7 +1065,7 @@ class Model { ...@@ -1070,7 +1065,7 @@ class Model {
['get', 'set'].forEach(type => { ['get', 'set'].forEach(type => {
const opt = `${type}terMethods`; const opt = `${type}terMethods`;
const funcs = _.clone(_.isObject(this.options[opt]) ? this.options[opt] : {}); const funcs = { ...this.options[opt] };
const _custom = type === 'get' ? this.prototype._customGetters : this.prototype._customSetters; const _custom = type === 'get' ? this.prototype._customGetters : this.prototype._customSetters;
_.each(funcs, (method, attribute) => { _.each(funcs, (method, attribute) => {
...@@ -2230,7 +2225,7 @@ class Model { ...@@ -2230,7 +2225,7 @@ class Model {
let instance = await this.findOne(options); let instance = await this.findOne(options);
if (instance === null) { if (instance === null) {
values = _.clone(options.defaults) || {}; values = { ...options.defaults };
if (_.isPlainObject(options.where)) { if (_.isPlainObject(options.where)) {
values = Utils.defaults(values, options.where); values = Utils.defaults(values, options.where);
} }
...@@ -2301,7 +2296,7 @@ class Model { ...@@ -2301,7 +2296,7 @@ class Model {
return [found, false]; return [found, false];
} }
values = _.clone(options.defaults) || {}; values = { ...options.defaults };
if (_.isPlainObject(options.where)) { if (_.isPlainObject(options.where)) {
values = Utils.defaults(values, options.where); values = Utils.defaults(values, options.where);
} }
...@@ -2379,7 +2374,7 @@ class Model { ...@@ -2379,7 +2374,7 @@ class Model {
); );
} }
let values = _.clone(options.defaults) || {}; let values = { ...options.defaults };
if (_.isPlainObject(options.where)) { if (_.isPlainObject(options.where)) {
values = Utils.defaults(values, options.where); values = Utils.defaults(values, options.where);
} }
...@@ -2580,7 +2575,7 @@ class Model { ...@@ -2580,7 +2575,7 @@ class Model {
// Validate // Validate
if (options.validate) { if (options.validate) {
const errors = []; const errors = [];
const validateOptions = _.clone(options); const validateOptions = { ...options };
validateOptions.hooks = options.individualHooks; validateOptions.hooks = options.individualHooks;
await Promise.all(instances.map(async instance => { await Promise.all(instances.map(async instance => {
...@@ -2598,12 +2593,14 @@ class Model { ...@@ -2598,12 +2593,14 @@ class Model {
} }
if (options.individualHooks) { if (options.individualHooks) {
await Promise.all(instances.map(async instance => { await Promise.all(instances.map(async instance => {
const individualOptions = _.clone(options); const individualOptions = {
...options,
validate: false,
hooks: true
};
delete individualOptions.fields; delete individualOptions.fields;
delete individualOptions.individualHooks; delete individualOptions.individualHooks;
delete individualOptions.ignoreDuplicates; delete individualOptions.ignoreDuplicates;
individualOptions.validate = false;
individualOptions.hooks = true;
await instance.save(individualOptions); await instance.save(individualOptions);
})); }));
...@@ -3141,10 +3138,12 @@ class Model { ...@@ -3141,10 +3138,12 @@ class Model {
} }
} else { } else {
instances = await Promise.all(instances.map(async instance => { instances = await Promise.all(instances.map(async instance => {
const individualOptions = _.clone(options); const individualOptions = {
...options,
hooks: false,
validate: false
};
delete individualOptions.individualHooks; delete individualOptions.individualHooks;
individualOptions.hooks = false;
individualOptions.validate = false;
return instance.save(individualOptions); return instance.save(individualOptions);
})); }));
...@@ -3562,7 +3561,7 @@ class Model { ...@@ -3562,7 +3561,7 @@ class Model {
this.dataValues = values; this.dataValues = values;
} }
// If raw, .changed() shouldn't be true // If raw, .changed() shouldn't be true
this._previousDataValues = _.clone(this.dataValues); this._previousDataValues = { ...this.dataValues };
} else { } else {
// Loop and call set // Loop and call set
if (options.attributes) { if (options.attributes) {
...@@ -3589,7 +3588,7 @@ class Model { ...@@ -3589,7 +3588,7 @@ class Model {
if (options.raw) { if (options.raw) {
// If raw, .changed() shouldn't be true // If raw, .changed() shouldn't be true
this._previousDataValues = _.clone(this.dataValues); this._previousDataValues = { ...this.dataValues };
} }
} }
return this; return this;
......
...@@ -194,7 +194,7 @@ class QueryInterface { ...@@ -194,7 +194,7 @@ class QueryInterface {
async createTable(tableName, attributes, options, model) { async createTable(tableName, attributes, options, model) {
let sql = ''; let sql = '';
options = _.clone(options) || {}; options = { ...options };
if (options && options.uniqueKeys) { if (options && options.uniqueKeys) {
_.forOwn(options.uniqueKeys, uniqueKey => { _.forOwn(options.uniqueKeys, uniqueKey => {
...@@ -244,7 +244,7 @@ class QueryInterface { ...@@ -244,7 +244,7 @@ class QueryInterface {
*/ */
async dropTable(tableName, options) { async dropTable(tableName, options) {
// if we're forcing we should be cascading unless explicitly stated otherwise // if we're forcing we should be cascading unless explicitly stated otherwise
options = _.clone(options) || {}; options = { ...options };
options.cascade = options.cascade || options.force || false; options.cascade = options.cascade || options.force || false;
let sql = this.QueryGenerator.dropTableQuery(tableName, options); let sql = this.QueryGenerator.dropTableQuery(tableName, options);
...@@ -913,7 +913,7 @@ class QueryInterface { ...@@ -913,7 +913,7 @@ class QueryInterface {
let indexes = []; let indexes = [];
let indexFields; let indexFields;
options = _.clone(options); options = { ...options };
if (!Utils.isWhereEmpty(where)) { if (!Utils.isWhereEmpty(where)) {
wheres.push(where); wheres.push(where);
...@@ -994,7 +994,7 @@ class QueryInterface { ...@@ -994,7 +994,7 @@ class QueryInterface {
* @returns {Promise} * @returns {Promise}
*/ */
async bulkInsert(tableName, records, options, attributes) { async bulkInsert(tableName, records, options, attributes) {
options = _.clone(options) || {}; options = { ...options };
options.type = QueryTypes.INSERT; options.type = QueryTypes.INSERT;
const results = await this.sequelize.query( const results = await this.sequelize.query(
...@@ -1006,7 +1006,7 @@ class QueryInterface { ...@@ -1006,7 +1006,7 @@ class QueryInterface {
} }
async update(instance, tableName, values, identifier, options) { async update(instance, tableName, values, identifier, options) {
options = _.clone(options || {}); options = { ...options };
options.hasTrigger = !!(instance && instance._modelOptions && instance._modelOptions.hasTrigger); options.hasTrigger = !!(instance && instance._modelOptions && instance._modelOptions.hasTrigger);
const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes); const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes);
...@@ -1053,7 +1053,7 @@ class QueryInterface { ...@@ -1053,7 +1053,7 @@ class QueryInterface {
const cascades = []; const cascades = [];
const sql = this.QueryGenerator.deleteQuery(tableName, identifier, {}, instance.constructor); const sql = this.QueryGenerator.deleteQuery(tableName, identifier, {}, instance.constructor);
options = _.clone(options) || {}; options = { ...options };
// Check for a restrict field // Check for a restrict field
if (!!instance.constructor && !!instance.constructor.associations) { if (!!instance.constructor && !!instance.constructor.associations) {
......
...@@ -751,7 +751,7 @@ class Sequelize { ...@@ -751,7 +751,7 @@ class Sequelize {
* @returns {Promise} * @returns {Promise}
*/ */
async sync(options) { async sync(options) {
options = _.clone(options) || {}; options = { ...options };
options.hooks = options.hooks === undefined ? true : !!options.hooks; options.hooks = options.hooks === undefined ? true : !!options.hooks;
options = _.defaults(options, this.options.sync, this.options); options = _.defaults(options, this.options.sync, this.options);
......
...@@ -263,8 +263,11 @@ function toDefaultValue(value, dialect) { ...@@ -263,8 +263,11 @@ function toDefaultValue(value, dialect) {
if (value instanceof DataTypes.NOW) { if (value instanceof DataTypes.NOW) {
return now(dialect); return now(dialect);
} }
if (_.isPlainObject(value) || Array.isArray(value)) { if (Array.isArray(value)) {
return _.clone(value); return value.slice();
}
if (_.isPlainObject(value)) {
return { ...value };
} }
return value; return value;
} }
......
...@@ -6,8 +6,7 @@ const chai = require('chai'), ...@@ -6,8 +6,7 @@ const chai = require('chai'),
sinon = require('sinon'), sinon = require('sinon'),
Config = require('../../../config/config'), Config = require('../../../config/config'),
ConnectionManager = require('../../../../lib/dialects/abstract/connection-manager'), ConnectionManager = require('../../../../lib/dialects/abstract/connection-manager'),
Pool = require('sequelize-pool').Pool, Pool = require('sequelize-pool').Pool;
_ = require('lodash');
const baseConf = Config[Support.getTestDialect()]; const baseConf = Config[Support.getTestDialect()];
const poolEntry = { const poolEntry = {
...@@ -43,8 +42,8 @@ describe('Connection Manager', () => { ...@@ -43,8 +42,8 @@ describe('Connection Manager', () => {
it('should initialize a multiple pools with replication', () => { it('should initialize a multiple pools with replication', () => {
const options = { const options = {
replication: { replication: {
write: _.clone(poolEntry), write: { ...poolEntry },
read: [_.clone(poolEntry), _.clone(poolEntry)] read: [{ ...poolEntry }, { ...poolEntry }]
} }
}; };
const sequelize = Support.createSequelizeInstance(options); const sequelize = Support.createSequelizeInstance(options);
...@@ -60,14 +59,14 @@ describe('Connection Manager', () => { ...@@ -60,14 +59,14 @@ describe('Connection Manager', () => {
return; return;
} }
const slave1 = _.clone(poolEntry); const slave1 = { ...poolEntry };
const slave2 = _.clone(poolEntry); const slave2 = { ...poolEntry };
slave1.host = 'slave1'; slave1.host = 'slave1';
slave2.host = 'slave2'; slave2.host = 'slave2';
const options = { const options = {
replication: { replication: {
write: _.clone(poolEntry), write: { ...poolEntry },
read: [slave1, slave2] read: [slave1, slave2]
} }
}; };
...@@ -106,13 +105,13 @@ describe('Connection Manager', () => { ...@@ -106,13 +105,13 @@ describe('Connection Manager', () => {
}); });
it('should allow forced reads from the write pool', () => { it('should allow forced reads from the write pool', () => {
const master = _.clone(poolEntry); const master = { ...poolEntry };
master.host = 'the-boss'; master.host = 'the-boss';
const options = { const options = {
replication: { replication: {
write: master, write: master,
read: [_.clone(poolEntry)] read: [{ ...poolEntry }]
} }
}; };
const sequelize = Support.createSequelizeInstance(options); const sequelize = Support.createSequelizeInstance(options);
......
...@@ -5,8 +5,7 @@ const chai = require('chai'), ...@@ -5,8 +5,7 @@ const chai = require('chai'),
Support = require('../support'), Support = require('../support'),
current = Support.sequelize, current = Support.sequelize,
sinon = require('sinon'), sinon = require('sinon'),
DataTypes = require('../../../lib/data-types'), DataTypes = require('../../../lib/data-types');
_ = require('lodash');
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
...@@ -22,7 +21,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -22,7 +21,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
beforeEach(function() { beforeEach(function() {
this.deloptions = { where: { secretValue: '1' } }; this.deloptions = { where: { secretValue: '1' } };
this.cloneOptions = _.clone(this.deloptions); this.cloneOptions = { ...this.deloptions };
this.stubDelete.resetHistory(); this.stubDelete.resetHistory();
}); });
......
...@@ -5,8 +5,7 @@ const chai = require('chai'), ...@@ -5,8 +5,7 @@ const chai = require('chai'),
Support = require('../support'), Support = require('../support'),
current = Support.sequelize, current = Support.sequelize,
sinon = require('sinon'), sinon = require('sinon'),
DataTypes = require('../../../lib/data-types'), DataTypes = require('../../../lib/data-types');
_ = require('lodash');
describe(Support.getTestDialectTeaser('Model'), () => { describe(Support.getTestDialectTeaser('Model'), () => {
describe('method update', () => { describe('method update', () => {
...@@ -20,7 +19,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -20,7 +19,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
beforeEach(function() { beforeEach(function() {
this.stubUpdate = sinon.stub(current.getQueryInterface(), 'bulkUpdate').resolves([]); this.stubUpdate = sinon.stub(current.getQueryInterface(), 'bulkUpdate').resolves([]);
this.updates = { name: 'Batman', secretValue: '7' }; this.updates = { name: 'Batman', secretValue: '7' };
this.cloneUpdates = _.clone(this.updates); this.cloneUpdates = { ...this.updates };
}); });
afterEach(function() { afterEach(function() {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!