2020-09-15 18:35:00 +08:00
|
|
|
|
/**
|
|
|
|
|
* 控制器基类
|
|
|
|
|
* @authors yutent (yutent@doui.cc)
|
|
|
|
|
* @date 2016-01-02 23:19:16
|
|
|
|
|
*
|
|
|
|
|
*/
|
|
|
|
|
|
2020-09-16 20:10:24 +08:00
|
|
|
|
import Smarty from 'smartyx' //模板引擎
|
2020-09-15 18:35:00 +08:00
|
|
|
|
|
2020-09-16 20:10:24 +08:00
|
|
|
|
import { sign, verify } from '../module/jwt.js'
|
|
|
|
|
|
|
|
|
|
const smarty = new Smarty()
|
2020-09-15 18:35:00 +08:00
|
|
|
|
|
2020-09-16 14:08:06 +08:00
|
|
|
|
export default class Controller {
|
2020-09-15 18:35:00 +08:00
|
|
|
|
constructor({ ctx, req, res }) {
|
|
|
|
|
this.ctx = ctx
|
|
|
|
|
this.name = req.app
|
|
|
|
|
this.request = req
|
|
|
|
|
this.response = res
|
|
|
|
|
|
|
|
|
|
this.jwt = {
|
2020-09-16 20:10:24 +08:00
|
|
|
|
sign: sign.bind(this),
|
|
|
|
|
result: verify.call(this)
|
2020-09-15 18:35:00 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
smarty.config('path', this.ctx.get('VIEWS'))
|
|
|
|
|
smarty.config('ext', this.ctx.get('temp_ext'))
|
|
|
|
|
smarty.config('cache', !!this.ctx.get('temp_cache'))
|
|
|
|
|
|
|
|
|
|
this.cookie = this.ctx.ins('cookie')
|
|
|
|
|
this.session = this.ctx.ins('session')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//定义一个变量,类似于smarty,把该
|
|
|
|
|
assign(key, val) {
|
|
|
|
|
key += ''
|
|
|
|
|
if (!key) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (val === undefined || val === null) {
|
|
|
|
|
val = ''
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
smarty.assign(key, val)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//模板渲染, 参数是模板名, 可不带后缀, 默认是 .tpl
|
|
|
|
|
render(file, noParse = false) {
|
|
|
|
|
smarty
|
|
|
|
|
.render(file, noParse)
|
|
|
|
|
.then(html => {
|
|
|
|
|
this.response.render(html)
|
|
|
|
|
})
|
|
|
|
|
.catch(err => {
|
|
|
|
|
this.response.error(err)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RESFULL-API规范的纯API返回
|
|
|
|
|
send(status = 200, msg = 'success', data = {}) {
|
|
|
|
|
if (typeof msg === 'object') {
|
|
|
|
|
data = msg
|
|
|
|
|
msg = 'success'
|
|
|
|
|
}
|
|
|
|
|
this.response.send(status, msg, data)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//针对框架定制的debug信息输出
|
|
|
|
|
xdebug(err) {
|
|
|
|
|
let msg = err
|
|
|
|
|
if (this.ctx.get('debug')) {
|
|
|
|
|
msg = err.stack || err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
this.response.append('X-debug', msg + '')
|
|
|
|
|
}
|
|
|
|
|
}
|