UNPKG

generic-repository

Version:

Generic repository pattern implementation for node.js. Currently supports mongo and in-memory(testing) databases.

54 lines (53 loc) 2.6 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const mongodb_1 = require("mongodb"); // Singleton, in order to make sure repositories share a connection/db class MongoConnect { constructor() { } static get Instance() { return this._instance || (this._instance = new this()); } connect(connectionString = undefined, database = undefined) { return __awaiter(this, void 0, void 0, function* () { let dbUri = connectionString || process.env.DB_URI; let dbName = database || process.env.DB_NAME; if (process.env.NODE_ENV === 'test' && process.env.DB_URI_TEST) { console.log('Running in ', process.env.NODE_ENV, ' environment'); dbUri = process.env.DB_URI_TEST; dbName = process.env.DB_NAME_TEST; } if (!connectionString) { console.warn('No connectionString found! Make sure you either pass it to the mongo connect, or have it defined in your enviroment settings(DB_URI)'); } else if (!database) { console.warn('No database specified! Make sure you either pass it to the mongo connect, or have it defined in your enviroment settings(DB_NAME)'); } console.log(this, 'Connecting to database..'); return this._connection = mongodb_1.MongoClient.connect(dbUri).then((ready) => { console.log('Connected!'); this._readyConnection = ready; return this._db = ready.db(dbName); }).catch(error => console.log('Failed to connect to', dbUri, error)); }); } get connection() { return this._connection; } get db() { return this._db; } gracefulExit() { this._readyConnection && this._readyConnection.close(); } } exports.MongoConnect = MongoConnect; exports.MongoConnection = MongoConnect.Instance; exports.default = exports.MongoConnection;