UNPKG

@codemask-labs/nestjs-mongodb

Version:
79 lines 3.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DataSource = void 0; const common_1 = require("@nestjs/common"); const mongodb_1 = require("mongodb"); const collection_1 = require("./collection"); const utils_1 = require("./utils"); class DataSource { client; options; logger = new common_1.Logger(DataSource.name); db; constructor(client, options) { this.client = client; this.options = options; this.db = client.db(options.database, options.dbOptions); } getDatabaseName() { return this.db.databaseName; } getCollection(entity) { const metadata = (0, utils_1.getEntityMetadata)(entity); if (!metadata.collectionName) { throw new Error(`Only entities can have collections. Please make sure your [class ${entity.name}] is properly decorated with @Entity(collectionName: string).`); } return new collection_1.Collection(this.db, metadata.collectionName); } validate(entity, options) { const metadata = (0, utils_1.getEntityMetadata)(entity); if (!metadata.collectionName) { throw new Error(`Only entities can have collections. Please make sure your [class ${entity.name}] is properly decorated with @Entity(collectionName: string).`); } return this.db.admin().validateCollection(metadata.collectionName, options); } async synchronize() { if (!this.options.synchronize) { return; } const entities = (0, utils_1.getEntitiesFromMixedList)(this.options.entities); await Promise.all(entities.map(async (entity) => { const metadata = (0, utils_1.getEntityMetadata)(entity); if (!metadata.collectionName) { throw new Error(`Missing collection name on entity [class ${entity.name}]. Please make sure it is properly decorated with @Entity(collectionName: string) decorator.`); } const entityIndexes = (0, utils_1.getEntityIndexes)(metadata); const entityIndexDescriptions = (0, utils_1.getEntityIndexDescriptions)(entityIndexes); await this.db.createCollection(metadata.collectionName).catch((error) => { if (error.code === 48) { return; } throw error; }); await this.db.command({ collMod: metadata.collectionName, validator: (0, utils_1.getEntitySchemaValidator)(metadata.entityColumns) }); if (entityIndexDescriptions.length) { const collection = this.getCollection(entity); const currentIndexDescriptions = await collection.indexes(); const dropIndexNames = (0, utils_1.getEntityDropIndexNames)(currentIndexDescriptions, entityIndexes); await Promise.all(dropIndexNames.map(indexName => collection.dropIndex(indexName))); await collection.createIndexes(entityIndexDescriptions); } })); } connect() { return this.client.connect(); } close(force) { return this.client.close(force); } static createFromOptions(options) { const uri = (0, utils_1.getConnectionString)(options); const client = new mongodb_1.MongoClient(uri, options.clientOptions); return new DataSource(client, options); } } exports.DataSource = DataSource; //# sourceMappingURL=data-source.js.map