Instantiating All Models In BaseController a Good Approach?


#1

Hi guys my colleague created this approach of having a BaseController that loads all models so that we won’t have to call them in any controller we made and any Model we create is automatically instantiated.
My question Is that is there a disadvantage with this approach? I don’t have a complete understanding regarding how node works so help is greatly appreciated!

LoaderProvider

const { ServiceProvider } = require('@adonisjs/fold')
const _this = {}
const _ = require('lodash')

class LoaderProvider extends ServiceProvider {
this.app.singleton('Providers/Loader', () => {
  return {
      load: (dir) => {
          const collectionName = dir.split('/')[dir.split('/').length - 1]
          if (!_this[collectionName]) {
              const collection = {}
              const temp = use('require-all')(dir)
              let subDirectory = (value) => {
                  _.forEach(value, (_value, key) => {
                      if (typeof (_value) === 'function') {
                          collection[key] = _value
                      }
                      else {
                          subDirectory(_value)
                      }
                  })
              }
              _.forEach(temp, (value, key) => {
                  if (typeof (value) === 'function') {
                      collection[key] = value
                  }
                  else {
                      subDirectory(value)
                  }
              })
              _this[collectionName] = collection
          }
          return _this[collectionName]
      }
  }
})
}

BaseController

const _ = require('lodash')
const Helpers = use('Helpers')

class BaseController {
  constructor () {
    this._ = _
  }
}

_.forEach(
  use('require-all').load(`${use('Helpers').appRoot()}/app/Models`),
  (value, key) => {
    BaseController.prototype[key] = value
  }
)

module.exports = BaseController

UserController

const BaseController = use('App/Controllers/Http/BaseController')

class UserController extends BaseController {
  async index() {
    // Use any models using this
    const users = await this.User.all()

    // User lodash using this._
    const isArray = this._.isArray(users)
  }
}