UNPKG

1.06 kBJavaScriptView Raw
1const _ = require('lodash');
2const Promise = require('bluebird');
3const Cloudant = require('@cloudant/cloudant');
4
5const BATCH_UPDATE_CHUNK_SIZE = 100;
6
7const args = process.argv.slice(2);
8
9if (!args[1]) {
10 throw Error('No db specified');
11}
12
13const docFilter = doc => doc.type && /order|customer/.test(doc.type);
14
15const 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
29const batchUpdateDocs = (db, docs) => Promise.all(_.chunk(docs, BATCH_UPDATE_CHUNK_SIZE).map(chunk => db.bulk({ docs: chunk })));
30
31args.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});