-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
batchInsert.js
75 lines (63 loc) · 1.6 KB
/
batchInsert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const { isNumber, chunk, flatten } = require('lodash');
const delay = require('./delay');
module.exports = function batchInsert(
client,
tableName,
batch,
chunkSize = 1000
) {
let returning = void 0;
let autoTransaction = true;
let transaction = null;
const getTransaction = async () => {
if (transaction) {
autoTransaction = false;
return transaction;
}
autoTransaction = true;
return client.transaction();
};
const wrapper = 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);
const tr = await getTransaction();
try {
const chunksResults = [];
for (const items of chunks) {
chunksResults.push(await tr(tableName).insert(items, returning));
}
const result = flatten(chunksResults);
if (autoTransaction) {
await tr.commit();
}
return result;
} catch (error) {
if (autoTransaction) {
await tr.rollback(error);
}
throw error;
}
}),
{
returning(columns) {
returning = columns;
return this;
},
transacting(tr) {
transaction = tr;
return this;
},
}
);
return wrapper;
};