-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmongo-populate.js
301 lines (256 loc) · 8.28 KB
/
mongo-populate.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
const fs = require('fs'),
path = require('path'),
j2m = require('json2mongo'),
MongoClient = require('mongodb').MongoClient;
/**
* Async wrapper for fs.readfile
*/
async function readFileAsync(pathToFile) {
return new Promise((resolve, reject) => {
fs.readFile(pathToFile, async function (err, fileContents) {
if(err) {
reject(err);
} else {
resolve(fileContents);
}
});
});
}
/**
* Async wrapper for fs.readdir
*/
async function readFolderAsync(path) {
return new Promise((resolve,reject) => {
fs.readdir(path, function (err, files) {
if(err) {
reject(err);
} else {
resolve(files);
}
});
});
}
/**
* Asyncronously wrapper for fs.stat
*/
async function fsStatAsync(input) {
return new Promise((resolve, reject) => {
fs.stat(input, (err, stats) => {
if (err) {
reject(err);
} else {
resolve(stats);
}
});
});
}
class MongoPopulate {
constructor({
host,
port = 27017,
dbname,
username,
password,
overwrite = false,
verbose = false
}) {
if (!host || !dbname) {
throw new Error('No host name or database name provided');
}
this.host = host;
this.port = port;
this.dbname = dbname;
this.username = username;
this.password = password;
this.overwrite = overwrite;
this.verbose = verbose;
this.db = null;
this.connection = null;
}
/**
* Promisify connection to ensure all calls to seed() begin with this.db being set correctly.
*/
async connect() {
let credentials = '';
if(this.username && this.password) {
credentials = `${this.username}:${this.password}@`;
}
try {
this.connection = await MongoClient.connect(`mongodb://${credentials}${this.host}:${this.port}`);
}
catch(err) {
throw err;
}
this.db = this.connection.db(this.dbname);
}
/**
* Seeds the mongo database with the seed data passed, based on it's type.
* @public
* @param seedData - Data or path to JSON with which to populate the collection.
* Can be in one of 3 formats:
* - Path to directory containing JSON files
* - Path to singular JSON file
* - Single array of collection data (requires collection name to be specified)
* @param collectionName - Optional parameter to override collection name. Required
* @return Promise
*/
async seed(seedData, collectionName) {
await this.connect();
if (Array.isArray(seedData)) {
if (!collectionName) {
throw new Error('Must provide a collection name if providing collection data as an array.');
} else {
return this.populateFromData(seedData, collectionName);
}
}
try {
const seedDataType = await fsStatAsync(seedData);
if (seedDataType.isDirectory()) {
return this.populateFromFolder(seedData);
} else if (seedDataType.isFile()) {
return this.readJsonFileAndInsert(null, seedData);
}
} catch(e) {
throw(e);
}
}
/**
* Populate the mongodb collection from a file folder
* @private
* @param seedDataDir The directory containing JSON collection files
* @return Promise
*/
async populateFromFolder(seedDataDir) {
let promises = [],
files;
try {
files = await readFolderAsync(seedDataDir);
} catch(e) {
throw(e);
}
files.forEach(file => {
if (path.extname(file) != '.json') {
throw(new Error('Please ensure all files are in JSON format'));
}
promises.push(this.readJsonFileAndInsert(seedDataDir, file));
});
return Promise.all(promises);
}
/**
* Populate the mongodb collection from collection data or array of collection data.
* @private
* @param data An array of collection data
* @param collectionName The name of the collection to operate on.
* @return Promise
*/
async populateFromData(data, collectionName) {
let collection, collectionExists;
// Drop collection entirely to destroy all indexes, if overwrite specified.
if (this.overwrite) {
try {
collectionExists = await this.collectionExists(collectionName);
if (collectionExists) {
await this.db.dropCollection(collectionName);
await this.db.createCollection(collectionName);
}
} catch(e) {
throw(e);
}
}
collection = await this.db.collection(collectionName);
return this.insertRecords(data, collection);
}
/**
*
* @param {String} collectionName
* @return {Promise<Boolean>} exists
*/
async collectionExists(collectionName) {
const collections = await this.db.listCollections().toArray();
let contains = false;
collections.forEach(collection => {
if(collection.name === collectionName) {
contains = true;
}
});
return contains;
}
async readJsonFileAndInsert(seedDataDir, file) {
const me = this,
pathToFile = seedDataDir ? path.join(seedDataDir, file) : file,
collectionName = path.basename(file, '.json');
let collection,
collectionExists,
fileContents;
try {
fileContents = await readFileAsync(pathToFile);
} catch(e) {
throw(e);
}
if (!fileContents) {
throw(new Error(`File ${file} is empty`));
}
// Drop collection entirely to destroy all indexes, if overwrite specified.
if (me.overwrite) {
try {
collectionExists = await me.collectionExists(collectionName);
if (collectionExists) {
await me.db.dropCollection(collectionName);
await me.db.createCollection(collectionName);
}
} catch(e) {
throw(e);
}
}
collection = await me.db.collection(collectionName);
let data = j2m(JSON.parse(fileContents));
return me.insertRecords(data, collection);
}
/**
* Handler for promise rejection based anticipated Mongo errors.
* @param {MongoError|insertOneWriteOpResultObject} err
*/
async handleInsertion(results) {
let finishedWithoutException = true,
skipCount = 0;
results.forEach(result => {
if(result instanceof Error && result.code === 11000) {
skipCount++;
if(this.verbose) {
console.log(`Duplicate id found, skipping record. Full message: ${result.message}`);
}
} else if (result instanceof Error) {
finishedWithoutException = false;
throw(result);
}
});
if(finishedWithoutException) {
if(!this.overwrite) {
console.log(`Skipped ${skipCount} duplicate records`);
}
await this.connection.close();
return true;
}
}
/**
*
* @param {Record[]} data
* @param {MongoCollection} collection
*/
async insertRecords(data, collection) {
// Map all insertions to promise.
let promises = data.map(record => {
return new Promise(resolve => {
collection.insert(record, { w: 1}, (err, result) => {
if(err) {
resolve(err);
} else {
resolve(result);
}
});
});
});
return Promise.all(promises).then(this.handleInsertion.bind(this));
}
}
module.exports = MongoPopulate;