method_model_exists.js

import resolveMethod from '../../lib/resolve-method.js'

const cache = {}

/**
 * Check if model exists already
 *
 * @method
 * @memberof Dobo
 * @async
 * @instance
 * @name modelExists
 * @param {string} name - Model's name
 * @param {boolean} [thrown=false] - If ```true``` throw error if not exists instead of just silent
 * @param {Object} [options={}] - Options object
 * @returns {boolean}
 */
async function exists (name, thrown, options = {}) {
  if (cache[name]) return cache[name]
  const { runHook } = this.app.bajo
  const { camelCase } = this.app.lib._
  const { handler, schema, driver } = await resolveMethod.call(this, name, 'model-exists', options)
  if (!options.noHook) {
    await runHook(`${this.ns}:beforeModelExists`, schema, options)
    await runHook(`${this.ns}.${camelCase(name)}:beforeModelExists`, options)
  }
  const exist = await handler.call(this.app[driver.ns], { schema, options })
  if (!options.noHook) {
    await runHook(`${this.ns}.${camelCase(name)}:afterModelExists`, exist, options)
    await runHook(`${this.ns}:afterModelExists`, schema, exist, options)
  }
  if (!exist && thrown) throw this.error('modelNotExists%s', name)
  cache[name] = exist
  return exist
}

export default exists