1 | const _ = require('lodash');
|
2 | const Promise = require('bluebird');
|
3 | const Cloudant = require('@cloudant/cloudant');
|
4 |
|
5 | const BATCH_UPDATE_CHUNK_SIZE = 100;
|
6 |
|
7 | const args = process.argv.slice(2);
|
8 |
|
9 | if (!args[1]) {
|
10 | throw Error('No db specified');
|
11 | }
|
12 |
|
13 | const docFilter = doc => doc.type && /order|customer/.test(doc.type);
|
14 |
|
15 | const docMutate = (doc) => {
|
16 | if (!doc.modifiedAt) {
|
17 | doc.modifiedAt = doc.modified;
|
18 | delete doc.modified;
|
19 | }
|
20 |
|
21 | if (!doc.createdAt) {
|
22 | doc.createdAt = doc.created;
|
23 | delete doc.created;
|
24 | }
|
25 |
|
26 | return doc;
|
27 | };
|
28 |
|
29 | const batchUpdateDocs = (db, docs) => Promise.all(_.chunk(docs, BATCH_UPDATE_CHUNK_SIZE).map(chunk => db.bulk({ docs: chunk })));
|
30 |
|
31 | args.forEach(async (dbName) => {
|
32 | const db = new Cloudant({
|
33 | url: args[0],
|
34 | plugins: ['promises', 'retry'],
|
35 | }).db.use(dbName);
|
36 |
|
37 | let docs = (await db.list({ include_docs: true })).rows.map(row => row.doc);
|
38 |
|
39 | docs = docs.filter(docFilter);
|
40 |
|
41 | docs = docs.map(docMutate);
|
42 |
|
43 | await batchUpdateDocs(db, docs);
|
44 |
|
45 | console.log(`${dbName} --> ${docs.length} orders/customers updated`);
|
46 | });
|