UNPKG

@xanhz/mongo-tools

Version:

A NodeJS package for Mongo Tools

88 lines 3.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MongoTools = void 0; const bson_1 = require("bson"); const child_process_1 = require("child_process"); const _ = require("./lodash"); var MongoTools; (function (MongoTools) { const MultiFields = ['excludeCollection', 'excludeCollectionsWithPrefix', 'nsExclude', 'nsInclude']; class MongoToolsError extends Error { constructor(code, signal) { if (code == null) { super(`Execute command failed`); } else { super(`Execute command failed with code ${code}`); } this.code = code; this.signal = signal; } } function toArgs(options) { return Object.entries(options).map(([key, value]) => { if (_.isTrue(value)) { return `--${key}`; } if (_.isArray(value)) { if (MultiFields.includes(key)) { return value.map((item) => `--${key}=${item}`).join(' '); } return `--${key}=${value.join(',')}`; } if (_.isObject(value)) { return `--${key}=${bson_1.EJSON.stringify(value, undefined, 0)}`; } return `--${key}=${value}`; }); } function run(command, options) { const args = toArgs(options); return new Promise((resolve, reject) => { const stream = (0, child_process_1.spawn)(command, args); stream.on('error', (error) => reject(error)); stream.stdout.on('data', (message) => { console.log(message.toString()); }); stream.stderr.on('data', (message) => { console.log(message.toString()); }); stream.on('close', (code, signal) => { if (code === 0) { return resolve(void 0); } const error = new MongoToolsError(code, signal); return reject(error); }); }); } /** * @tutorial https://www.mongodb.com/docs/database-tools/mongodump */ function $dump(options) { return run('mongodump', options); } MongoTools.$dump = $dump; /** * @tutorial https://www.mongodb.com/docs/database-tools/mongorestore */ function $restore(options) { return run('mongorestore', options); } MongoTools.$restore = $restore; /** * @tutorial https://www.mongodb.com/docs/database-tools/mongoimport */ function $import(options) { return run('mongoimport', options); } MongoTools.$import = $import; /** * @tutorial https://www.mongodb.com/docs/database-tools/mongoexport */ function $export(options) { return run('mongoexport', options); } MongoTools.$export = $export; })(MongoTools || (exports.MongoTools = MongoTools = {})); //# sourceMappingURL=commands.js.map