-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathupdate_documents.js
More file actions
188 lines (168 loc) · 5.33 KB
/
Copy pathupdate_documents.js
File metadata and controls
188 lines (168 loc) · 5.33 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
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
188
/**
* ### Модуль перезаписи документов
*
* - удаление документа
*
* @module update_documents
*
* Created 14.01.2019
*/
/**
* ### Переменные окружения
* DEBUG "wb:*,-not_this"
* ZONE 21
* DBUSER admin
* DBPWD admin
* COUCHPATH http://cou221:5984/wb_
*/
'use strict';
const debug = require('debug')('wb:update_documents');
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')
.alias('a', 'action').nargs('a', 1).describe('a', 'Action with document')
.version('v', 'Show version', '0.0.1').alias('v', 'version')
.help('h').alias('h', 'help')
.example('node update_document id cat.characteristics|00000000-0000-0000-0000-000000000000', 'Update document with id `cat.characteristics|00000000-0000-0000-0000-000000000000`, database by default wb_21_doc')
.example('node update_document json_file file.json', 'Update documents from JSON file `file.json` in database wb_21_doc')
.command(
'id [name]',
'Update document id `name`',
yargs => yargs.positional('name', {type: 'string', describe: 'Empty document id'}),
args => {
const { d, a, 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(() => update_document(db, name, a))
.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]',
'Update documents from JSON file `name`',
yargs => yargs.positional('name', {type: 'string', describe: 'Empty JSON file name'}),
args => {
const { d, a, 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 update_documents(db, json, a);
});
})
.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 update_documents(db, json, action) {
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 update_document(db, `${field}|${item.ref}`, action);
}
}
}
}
}
}
function update_document(db, id, action) {
console.log(`processing ${id} started`);
// запрашиваем документ
return db.get(id)
.then(doc => {
console.log(`${doc._id} loaded successful`);
if (action === 'delete' && doc._deleted !== true) {
doc._deleted = true;
}
// обновляем документ
return db.put(doc)
.then(() => {
console.log(`${doc._id} updated successful`);
})
.catch(err => {
console.log(`error update ${doc._id}: ${err && err.message}`);
});
})
.catch(err => {
console.log(`error get ${id}: ${err && err.message}`);
});
}