UNPKG

6.32 kBJavaScriptView Raw
1"use strict";
2var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3 if (k2 === undefined) k2 = k;
4 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5}) : (function(o, m, k, k2) {
6 if (k2 === undefined) k2 = k;
7 o[k2] = m[k];
8}));
9var __exportStar = (this && this.__exportStar) || function(m, exports) {
10 for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11};
12var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14 return new (P || (P = Promise))(function (resolve, reject) {
15 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18 step((generator = generator.apply(thisArg, _arguments || [])).next());
19 });
20};
21Object.defineProperty(exports, "__esModule", { value: true });
22exports.Seeder = void 0;
23const common_1 = require("./common");
24const database_1 = require("./database");
25const transformer_1 = require("./transformer");
26const importer_1 = require("./importer");
27const config_1 = require("./config");
28__exportStar(require("./config"), exports);
29__exportStar(require("./helpers"), exports);
30/**
31 * Allows to seed database. It is a main Mongo Seeding class.
32 */
33class Seeder {
34 /**
35 * Constructs a new `Seeder` instance and loads configuration for data import.
36 *
37 * @param config Optional partial object with database seeding configuration. The object is merged with the default configuration object. To use all default settings, simply omit this parameter.
38 */
39 constructor(config) {
40 /**
41 * Configuration for seeding database.
42 */
43 this.config = config_1.defaultSeederConfig;
44 /**
45 * Populates collections and their documents from given path.
46 * The path has to contain file structure described on https://github.com/pkosiec/mongo-seeding/blob/main/docs/import-data-definition.md.
47 *
48 * @param path File path
49 * @param partialConfig Optional partial collection reading configuration object. It is merged with default configuration object. To use all default settings, simply omit this parameter.
50 */
51 this.readCollectionsFromPath = (path, partialConfig) => {
52 const config = config_1.mergeCollectionReadingOptions(partialConfig);
53 let collections;
54 try {
55 const { CollectionPopulator } = require('./populator');
56 const populator = new CollectionPopulator(config.extensions, config.ejsonParseOptions, this.log);
57 this.log(`Reading collections from ${path}...`);
58 collections = populator.readFromPath(path);
59 }
60 catch (err) {
61 throw wrapError(err);
62 }
63 if (config.transformers.length > 0) {
64 this.log('Transforming collections...');
65 collections = new transformer_1.CollectionTransformer().transform(collections, config.transformers);
66 }
67 return collections;
68 };
69 /**
70 * Connects to a database and imports all collections.
71 *
72 * @param collections Array of collection definitions
73 * @param partialConfig Optional partial configuration object. Ita allows to change the database seeding configuration for single data import. It is merged with default configuration object. To use the configuration provided in `Seeder` constructor, simply omit this parameter.
74 */
75 this.import = (collections, partialConfig) => __awaiter(this, void 0, void 0, function* () {
76 if (collections.length === 0) {
77 this.log('No data to import. Finishing...');
78 return;
79 }
80 this.log('Starting collection import...');
81 const config = config_1.mergeSeederConfig(partialConfig, this.config);
82 const databaseConnector = new database_1.DatabaseConnector(config.databaseReconnectTimeout, config.mongoClientOptions, this.log);
83 let database;
84 try {
85 database = yield databaseConnector.connect(config.database);
86 if (!config.dropDatabase && config.dropCollections) {
87 this.log('Dropping collections...');
88 for (const collection of collections) {
89 yield database.dropCollectionIfExists(collection.name);
90 }
91 }
92 if (!config.dropDatabase && config.removeAllDocuments) {
93 this.log('Removing all documents from collections...');
94 const promises = collections.map((collection) => database.removeAllDocumentsIfCollectionExists(collection.name));
95 yield Promise.all(promises);
96 }
97 if (config.dropDatabase) {
98 this.log('Dropping database...');
99 yield database.drop();
100 }
101 yield new importer_1.CollectionImporter(database, config.collectionInsertManyOptions, this.log).import(collections);
102 }
103 catch (err) {
104 throw wrapError(err);
105 }
106 finally {
107 if (database) {
108 yield database.closeConnection();
109 }
110 }
111 this.log('Finishing...');
112 });
113 this.config = config_1.mergeSeederConfig(config);
114 this.log = common_1.NewLoggerInstance();
115 }
116}
117exports.Seeder = Seeder;
118/**
119 * Transformer functions for collections before data import.
120 */
121Seeder.Transformers = transformer_1.DefaultTransformers;
122/**
123 * Wraps error with custom name
124 *
125 * @param err Original error
126 */
127const wrapError = (err) => {
128 err.name = 'MongoSeedingError';
129 err.message = `${err.name}: ${err.message}`;
130 return err;
131};
132//# sourceMappingURL=index.js.map
\No newline at end of file