batchInsert.js
1.65 KB
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
import { isNumber, isArray, chunk, flatten, assign } from 'lodash';
import Promise from 'bluebird';
export default function batchInsert(client, tableName, batch, chunkSize = 1000) {
let returning = void 0;
let autoTransaction = true;
let transaction = null;
const getTransaction = () => new Promise((resolve, reject) => {
if(transaction) {
return resolve(transaction);
}
client.transaction(resolve)
.catch(reject);
});
const wrapper = assign(new Promise((resolve, reject) => {
const chunks = chunk(batch, chunkSize);
if(!isNumber(chunkSize) || chunkSize < 1) {
return reject(new TypeError(`Invalid chunkSize: ${chunkSize}`));
}
if(!isArray(batch)) {
return reject(new TypeError(`Invalid batch: Expected array, got ${typeof batch}`));
}
//Next tick to ensure wrapper functions are called if needed
return Promise.delay(1)
.then(getTransaction)
.then((tr) => {
return Promise.mapSeries(chunks, (items) => tr(tableName).insert(items, returning))
.then((result) => {
if(autoTransaction) {
tr.commit();
}
return flatten(result);
})
.catch((error) => {
if(autoTransaction) {
tr.rollback(error);
}
throw error;
})
})
.then(resolve)
.catch(reject);
}), {
returning(columns) {
returning = columns;
return this;
},
transacting(tr) {
transaction = tr;
autoTransaction = false;
return this;
}
});
return wrapper;
}