UNPKG

mares-connector

Version:

mares framework connector

102 lines (90 loc) 2.33 kB
const path = require('path') const fs = require('fs') const PrivateMethod = { async connectMongoose(mares, rootDir, modules, force) { let mongoose = mares.getMongoose() let dirs = fs.readdirSync(rootDir) const schemas = {} dirs.map((dir) => { modules.map((module) => { if (module === dir) { let collectionPath = path.resolve(rootDir, dir, 'infra/repositories/collections') let isExistCollectionPath = fs.existsSync(collectionPath) if (isExistCollectionPath) { let collections = require(collectionPath) for (let key in collections) { if (collections.hasOwnProperty(key)) { schemas[key] = collections[key] } } } } }) }) for (let key in schemas) { if (schemas.hasOwnProperty(key)) { let schema = schemas[key] mongoose.model(schema.options.collection, schema) } } if (force === true) { await this.dropMongoose() } }, async dropMongoose() { let mongoose = require('mongoose') if (Object.keys(mongoose.models).length > 0) { for (let key in mongoose.models) { if (mongoose.models.hasOwnProperty(key)) { await mongoose.models[key].deleteMany({}, {paranoid: false}) } } } } } /** * Mares connector class */ class MaresConnector { /** * constructor * @param {MaresWelder} mares - mares welder object * @param {Object} settings - setting object */ constructor(mares, settings) { this.settings = settings this.mares = mares } /** * 데이터베이스에 연결한다. 항상 startApp 전에 호출해 줘야한다. * @param {string} rootDir - project root dir * @returns {Promise<void>} */ async connectMongoose(rootDir) { let settings = this.settings await this.mares.connectMongoose(settings.config.mongoose.url) await PrivateMethod.connectMongoose( this.mares, rootDir, settings.modules, settings.config['mongoose'].force ) } /** * start application * @returns {Promise<Express>} */ async startApp() { let settings = this.settings return await this.mares.listen(process.env.PORT || settings.config['app'].port) } /** * stop application * @returns {Promise<void>} */ async stopApp(callBack) { await this.mares.getMongoose().disconnect() await this.mares.disconnectApp(callBack) } } module.exports = MaresConnector