mongo-seeding
Version:
The ultimate Node.js library for populating your MongoDB database.
179 lines • 5.97 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Database = void 0;
exports.parseSeederDatabaseConfig = parseSeederDatabaseConfig;
const connection_string_1 = require("connection-string");
/**
* Provides functionality for managing documents, collections in database.
*/
class Database {
/**
* Constructs a new `Database` object.
*
* @param mongoClient MongoDB Client
* @param log Optional logger
*/
constructor(mongoClient, log) {
this.client = mongoClient;
this.db = mongoClient.db();
this.log = log
? log
: () => {
// do nothing
};
}
/**
* Inserts documents into a given collection.
*
* @param documentsToInsert Array of documents, which are being imported
* @param collectionName Collection name
* @param bulkWriteOptions Optional collection import options
*/
insertDocumentsIntoCollection(documentsToInsert, collectionName, bulkWriteOptions) {
return __awaiter(this, void 0, void 0, function* () {
const documentsCopy = documentsToInsert.map((document) => (Object.assign({}, document)));
return this.db
.collection(collectionName)
.insertMany(documentsCopy, bulkWriteOptions);
});
}
/**
* Drops database.
*/
drop() {
return __awaiter(this, void 0, void 0, function* () {
return this.db.dropDatabase();
});
}
/**
* Checks if a given collection exist.
*
* @param collectionName Collection name
*/
ifCollectionExist(collectionName) {
return __awaiter(this, void 0, void 0, function* () {
const collections = yield this.db.collections();
return collections
.map((collection) => collection.collectionName)
.includes(collectionName);
});
}
/**
* Drops a given collection if exists.
*
* @param collectionName Collection name
*/
dropCollectionIfExists(collectionName) {
return __awaiter(this, void 0, void 0, function* () {
if (!(yield this.ifCollectionExist(collectionName))) {
return;
}
return this.db.collection(collectionName).drop();
});
}
/**
* Remove all documents from a given collection
* if it exists.
*
* @param collectionName Collection name
*/
removeAllDocumentsIfCollectionExists(collectionName) {
return __awaiter(this, void 0, void 0, function* () {
if (!(yield this.ifCollectionExist(collectionName))) {
return;
}
return this.db.collection(collectionName).deleteMany({});
});
}
/**
* Closes connection with database.
*/
closeConnection() {
return __awaiter(this, void 0, void 0, function* () {
this.log('Closing connection...');
if (!this.client) {
return;
}
yield this.client.close(true);
});
}
}
exports.Database = Database;
/**
* Parses a database config object or a connection URI into a ConnectionString.
* @param input The database config object or connection URI to parse.
* @param mergeWithDefaults Whether to merge the parsed config with default values.
*/
function parseSeederDatabaseConfig(input, disableMergingWithDefaults) {
const defaultParams = defaultConnParams();
let uri = null;
if (!input) {
return new connection_string_1.ConnectionString(null, defaultParams);
}
switch (typeof input) {
case 'object':
// parse the object into a URI first, and then parse the URI into a ConnectionString
uri = parseUriFromObject(input).toString();
break;
case 'string':
uri = input;
break;
default:
throw new Error('Connection URI or database config object is required to connect to database');
}
if (disableMergingWithDefaults) {
return new connection_string_1.ConnectionString(uri);
}
const out = new connection_string_1.ConnectionString(uri, defaultParams);
if (out.hosts && out.hosts.length > 1) {
out.hosts = [out.hosts[0]];
}
return out;
}
/**
* Parses a database config object into a URI.
* @param config The database config object to parse.
*/
function parseUriFromObject(config) {
return new connection_string_1.ConnectionString(null, {
protocol: config.protocol,
hosts: [
{
name: config.host,
port: config.port,
},
],
user: config.username,
password: config.password,
path: config.name ? [config.name] : undefined,
params: config.options,
});
}
/**
* Returns default connection parameters.
*/
function defaultConnParams() {
return {
protocol: 'mongodb',
hosts: [
{
name: '127.0.0.1',
port: 27017,
},
],
path: ['database'],
user: undefined,
password: undefined,
params: undefined,
};
}
//# sourceMappingURL=database.js.map