1.6.Module
// Allow dbConnection to be passed from outside. const AcceptsDbConnection = stampit() .init(function ({dbConnection}) { this.dbConnection = dbConnection; });
// Assigns the default connection string. const DefaultConnectionConfig = stampit() .init(function ({connectionConfig}) { // can pass the string as factory argument this.connectionConfig = connectionConfig; }) .props({ // if nothing was passed this value will be used connectionConfig: require('./config.json').db.connection });
// Adds .log() method to factory instantiated objects. const Logger = stampit() .methods({ log: console.log });
// The connection object. const DbConnection = stampit() .props({ // Assigns the mongoose connection object. dbConnection: mongoose.connection }) .compose( Logger, // add logging capability via this.log() DefaultConnectionConfig, // add the default this.connectionConfig value AcceptsDbConnection // allow passing dbConnection as argument ) .init(function () { // Connecting to the DB upon creating an object. if (!this.dbConnection.readyState) { this.dbConnection.open(this.connectionConfig); this.log('Opening a DB connection'); } }) .methods({ // A method to close the connection. close() { if (this.dbConnection.readyState) { this.dbConnection.close(); this.log('Closing the DB connection'); } } });
Last updated