|
| 1 | +const assert = require('assert') |
| 2 | +const debug = require('debug')('bear-core') |
| 3 | +const fs = require('fs') |
| 4 | +const isGeneratorFunction = require('is-generator-function') |
| 5 | +const convert = require('koa-convert') |
| 6 | +const KoaApplication = require('koa') |
| 7 | +const BEAR_LOADER = Symbol.for('bear#loader') |
| 8 | + |
| 9 | +class Bear extends KoaApplication { |
| 10 | + constructor (options = {}) { |
| 11 | + options.baseDir = options.baseDir || process.cwd() |
| 12 | + |
| 13 | + assert(typeof options.baseDir === 'string', 'options.baseDir required, and must be a string') |
| 14 | + assert(fs.existsSync(options.baseDir), `Directory ${options.baseDir} not exists`) |
| 15 | + assert(fs.statSync(options.baseDir).isDirectory(), `Directory ${options.baseDir} is not a directory`) |
| 16 | + super() |
| 17 | + |
| 18 | + this._options = options |
| 19 | + this.console = console |
| 20 | + |
| 21 | + const Loader = this[BEAR_LOADER] |
| 22 | + assert(Loader, 'Symbol.for(\'bear#loader\') is required') |
| 23 | + |
| 24 | + this.loader = new Loader({ |
| 25 | + baseDir: options.baseDir, |
| 26 | + app: this, |
| 27 | + plugins: options.plugins, |
| 28 | + logger: this.console |
| 29 | + }) |
| 30 | + } |
| 31 | + |
| 32 | + use (fn) { |
| 33 | + if (typeof fn !== 'function') throw new TypeError('middleware must be a function!') |
| 34 | + if (isGeneratorFunction(fn)) { |
| 35 | + fn = convert(fn) |
| 36 | + } |
| 37 | + debug('use %s', fn._name || fn.name || '-') |
| 38 | + this.middleware.push(fn) |
| 39 | + return this |
| 40 | + } |
| 41 | + |
| 42 | + get baseDir () { |
| 43 | + return this._options.baseDir |
| 44 | + } |
| 45 | + |
| 46 | + get [BEAR_LOADER] () { |
| 47 | + return require('./loader/bear_loader') |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +module.exports = Bear |
0 commit comments