-
Notifications
You must be signed in to change notification settings - Fork 3
/
resolve_conflicts.js
187 lines (168 loc) · 5.42 KB
/
resolve_conflicts.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/**
* ### Модуль разрешения конфликтов в пользу последнего
*
* @module resolve_conflicts
*
* Created 18.06.2019
*/
/**
* ### Переменные окружения
* DEBUG "wb:*,-not_this"
* ZONE 21
* DBUSER admin
* DBPWD admin
* COUCHPATH http://cou221:5984/wb_
*/
'use strict';
const debug = require('debug')('wb:resolve_conflicts');
const PouchDB = require('./pouchdb')
.plugin(require('pouchdb-find'));
const fs = require('fs');
debug('required');
const yargs = require('yargs')
.usage('Usage: $0 [options] <command>')
.demand(1)
.strict()
.alias('d', 'database').nargs('d', 1).describe('d', 'Database name')
.version('v', 'Show version', '0.0.1').alias('v', 'version')
.help('h').alias('h', 'help')
.example('node resolve_conflicts id cat.characteristics|00000000-0000-0000-0000-000000000000', 'Resolve conflicts in id `cat.characteristics|00000000-0000-0000-0000-000000000000`, database by default wb_21_doc')
.example('node resolve_conflicts json_file file.json', 'Resolve conflicts from JSON file `file.json` in database wb_21_doc')
.command(
'id [name]',
'Resolve conflicts in id `name`',
yargs => yargs.positional('name', {type: 'string', describe: 'Empty document id'}),
args => {
const { d, name } = args;
if (name) {
// инициализируем параметры сеанса и метаданные
const {ZONE, DBUSER, DBPWD, COUCHPATH} = process.env;
const prefix = 'wb_';
const path = d ? `${COUCHPATH.replace(prefix, '')}${d}` : `${COUCHPATH}${ZONE}_doc`;
const db = new PouchDB(path, {
auth: {
username: DBUSER,
password: DBPWD
},
skip_setup: true,
ajax: {timeout: 100000}
});
db.info()
.then(info => {
console.log(`connected to ${info.host}, doc count: ${info.doc_count}`);
})
.then(() => resolve_conflicts(db, name))
.then(() => {
console.log('all done');
})
.catch(err => {
console.log(`error find ${name}: ${err && err.message}`);
});
}
else {
yargs.showHelp();
process.exit(1);
}
}
)
.command(
'json_file [name]',
'Resolve conflicts from JSON file `name`',
yargs => yargs.positional('name', {type: 'string', describe: 'Empty JSON file name'}),
args => {
const { d, name } = args;
if (name) {
// инициализируем параметры сеанса и метаданные
const {ZONE, DBUSER, DBPWD, COUCHPATH} = process.env;
const prefix = 'wb_';
const path = d ? `${COUCHPATH.replace(prefix, '')}${d}` : `${COUCHPATH}${ZONE}_doc`;
const db = new PouchDB(path, {
auth: {
username: DBUSER,
password: DBPWD
},
skip_setup: true,
ajax: {timeout: 100000}
});
db.info()
.then(info => {
console.log(`connected to ${info.host}, doc count: ${info.doc_count}`);
})
.then(() => {
return new Promise((resolve, reject) => {
fs.readFile(name, {encoding: 'utf-8'}, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
})
.then(data => {
const json = JSON.parse(data);
if (!json) {
throw new Error({
error: true,
message: 'bad JSON format'
});
}
return resolve_from_json(db, json);
});
})
.then(() => {
console.log('all done');
})
.catch(err => {
console.log(`error update from ${name}: ${err && err.message}`);
});
}
else {
yargs.showHelp();
process.exit(1);
}
}
)
.epilog('\nMore information about the library: https://github.com/oknosoft/windowbuilder');
const {argv} = yargs;
if (!argv._.length) {
yargs.showHelp();
process.exit(1);
}
async function resolve_from_json(db, json) {
if (json.items && typeof json.items === 'object') {
for (const field in json.items) {
if (json.items[field] instanceof Array) {
for (const item of json.items[field]) {
if (typeof item === 'object' && item.ref) {
await resolve_conflicts(db, `${field}|${item.ref}`);
}
}
}
}
}
}
function resolve_conflicts(db, id) {
console.log(`processing ${id} started`);
// запрашиваем документ
return db.get(id, {conflicts: true})
.then(res => {
console.log(`${res._id} loaded successful`);
// удаляем конфликтные ревизии документа
if (res._conflicts) {
return res._conflicts.reduce((prev, rev) => {
return prev.then(() => {
return db.remove(res._id, rev)
.catch(err => {
console.log(`revision ${rev} cannot be remove: ${err && err.message}`);
});
});
}, Promise.resolve())
.then(() => {
console.log(`conflicts in ${res._id} resolved successful`);
});
}
})
.catch(err => {
console.log(`error get ${id}: ${err && err.message}`);
});
}