76 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			JavaScript
		
	
	
			
		
		
	
	
			76 lines
		
	
	
		
			1.9 KiB
		
	
	
	
		
			JavaScript
		
	
	
/**
 | 
						|
 * 路由中间件
 | 
						|
 * @author yutent<yutent.io@gmail.com>
 | 
						|
 * @date 2020/09/18 15:16:29
 | 
						|
 */
 | 
						|
 | 
						|
import { readonlyProp } from '../lib.js'
 | 
						|
 | 
						|
export function createRouter() {
 | 
						|
  return function (req, res, next) {
 | 
						|
    var debug = this.get('debug')
 | 
						|
    var spa = this.get('spa')
 | 
						|
 | 
						|
    // 1. 先判断控制器是否存在
 | 
						|
    if (!this.$load(spa ? 'index' : req.app)) {
 | 
						|
      return res.error(`Controller [${req.app}] not found`, 404)
 | 
						|
    }
 | 
						|
 | 
						|
    // 2. 默认二级路由为index
 | 
						|
    if (req.path.length < 1 && spa === false) {
 | 
						|
      req.path.push('index')
 | 
						|
    }
 | 
						|
 | 
						|
    // 3. 实例化控制器
 | 
						|
    this.$load(spa ? 'index' : req.app)
 | 
						|
      .then(async Module => {
 | 
						|
        let mod, route, act
 | 
						|
        let err = ''
 | 
						|
 | 
						|
        if (Module) {
 | 
						|
          mod = new Module()
 | 
						|
 | 
						|
          readonlyProp(mod, 'context', this)
 | 
						|
          readonlyProp(mod, 'request', req)
 | 
						|
          readonlyProp(mod, 'response', res)
 | 
						|
          readonlyProp(mod, 'name', req.app)
 | 
						|
 | 
						|
          // 4. 优先执行__main__方法
 | 
						|
          if (mod.__main__) {
 | 
						|
            try {
 | 
						|
              let r = await mod.__main__()
 | 
						|
              if (r === false) {
 | 
						|
                return
 | 
						|
              }
 | 
						|
            } catch (err) {
 | 
						|
              return Promise.reject(err)
 | 
						|
            }
 | 
						|
          }
 | 
						|
 | 
						|
          if (spa) {
 | 
						|
            return mod.indexAction.apply(mod, req.path)
 | 
						|
          } else {
 | 
						|
            route = req.path.shift()
 | 
						|
            act = route + 'Action'
 | 
						|
 | 
						|
            if (mod[act]) {
 | 
						|
              return mod[act].apply(mod, req.path)
 | 
						|
            } else {
 | 
						|
              err = new Error(`Action [${route}] not found`)
 | 
						|
              err.status = 404
 | 
						|
            }
 | 
						|
          }
 | 
						|
        } else {
 | 
						|
          err = new Error(`Controller [${req.app}] load error`)
 | 
						|
          err.status = 500
 | 
						|
        }
 | 
						|
 | 
						|
        return Promise.reject(err)
 | 
						|
      })
 | 
						|
      .catch(err => {
 | 
						|
        console.error(err)
 | 
						|
        res.error(debug ? err.stack || err : err, err.status || 500)
 | 
						|
      })
 | 
						|
  }
 | 
						|
}
 | 
						
          
          
            
              JavaScript
            
          
          100%