knex/lib/util/batchInsert.js
Bogdan Chadkin 6f817a3b6e
Avoid lodash typecheks (#4056)
* Avoid lodash typecheks

Lodash is quite big project. Even with direct imports it loads [tons](https://github.com/knex/knex/pull/3804) of
code and still bloats node_modules. Especially since lodash mostly used
as a polyfill for modern features.

In this diff I attempted to reduce lodash usage by replacing type checks
with `typeof` operator which might be sufficient.

Also replaced lodash/isObject with custom simplified utility which does not
consider functions as objects and allows to simplify code in one place.
2020-10-05 21:29:39 +03:00

60 lines
1.3 KiB
JavaScript

const chunk = require('lodash/chunk');
const flatten = require('lodash/flatten');
const delay = require('./delay');
const { isNumber } = require('./is');
module.exports = function batchInsert(
client,
tableName,
batch,
chunkSize = 1000
) {
let returning = void 0;
let transaction = null;
const runInTransaction = (cb) => {
if (transaction) {
return cb(transaction);
}
return client.transaction(cb);
};
return Object.assign(
Promise.resolve().then(async () => {
if (!isNumber(chunkSize) || chunkSize < 1) {
throw new TypeError(`Invalid chunkSize: ${chunkSize}`);
}
if (!Array.isArray(batch)) {
throw new TypeError(
`Invalid batch: Expected array, got ${typeof batch}`
);
}
const chunks = chunk(batch, chunkSize);
//Next tick to ensure wrapper functions are called if needed
await delay(1);
return runInTransaction(async (tr) => {
const chunksResults = [];
for (const items of chunks) {
chunksResults.push(await tr(tableName).insert(items, returning));
}
return flatten(chunksResults);
});
}),
{
returning(columns) {
returning = columns;
return this;
},
transacting(tr) {
transaction = tr;
return this;
},
}
);
};