controller/index.js

99 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-09-16 20:04:41 +08:00
/**
* 控制器基类
* @authors yutent (yutent@doui.cc)
* @date 2016-01-02 23:19:16
*
*/
2020-09-18 18:29:07 +08:00
import jwt from '@gm5/jwt'
2020-09-16 20:04:41 +08:00
export default class Controller {
constructor({ ctx, req, res }) {
2020-09-20 23:11:03 +08:00
this.context = ctx
2020-09-16 20:04:41 +08:00
this.name = req.app
this.request = req
this.response = res
2020-09-18 18:29:07 +08:00
jwt.expires = ctx.get('session').ttl
jwt.secret = ctx.get('jwt')
this.jwt = { sign: jwt.sign }
2020-09-16 20:04:41 +08:00
2020-09-20 23:11:03 +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'))
2020-09-16 20:04:41 +08:00
2020-09-20 23:11:03 +08:00
// this.session = this.ctx.ins('session')
2020-09-16 20:04:41 +08:00
}
//定义一个变量类似于smarty把该
2020-09-20 23:11:03 +08:00
// assign(key, val) {
// key += ''
// if (!key) {
// return
// }
2020-09-16 20:04:41 +08:00
2020-09-20 23:11:03 +08:00
// if (val === undefined || val === null) {
// val = ''
// }
2020-09-16 20:04:41 +08:00
2020-09-20 23:11:03 +08:00
// smarty.assign(key, val)
// }
2020-09-16 20:04:41 +08:00
//模板渲染, 参数是模板名, 可不带后缀, 默认是 .tpl
2020-09-20 23:11:03 +08:00
// render(file, noParse = false) {
// smarty
// .render(file, noParse)
// .then(html => {
// this.response.render(html)
// })
// .catch(err => {
// this.response.error(err)
// })
// }
2020-09-16 20:04:41 +08:00
checkAuth() {
this.jwt.result = jwt.verify(this.request.header('authorized'))
}
// cookie读写
cookie(key, val, opt) {
if (arguments.length < 2) {
return this.request.cookie(key)
}
if (!opt) {
opt = {}
}
opt.domain = opt.domain || this.context.get('domain')
if (val === null || val === undefined) {
delete opt.expires
opt.maxAge = -1
}
this.response.cookie(key, val, opt)
}
2020-09-16 20:04:41 +08:00
// 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) {
2020-09-20 23:11:03 +08:00
var msg = err
2020-09-16 20:04:41 +08:00
if (this.ctx.get('debug')) {
2020-09-20 23:11:03 +08:00
msg = err.message || err
2020-09-16 20:04:41 +08:00
}
2020-09-20 23:11:03 +08:00
msg = encodeURIComponent(msg + '')
this.response.append('X-debug', msg)
2020-09-16 20:04:41 +08:00
}
}