/** * 控制器基类 * @author yutent * @date 2020/09/24 15:45:17 */ export default class Controller { #auth = null // 定义一个模板变量 assign(key, val) { if (val === undefined || val === null) { val = '' } key += '' if (key) { this.context.$$views.assign(key, val) } } // 模板渲染, 参数是模板名, 可不带后缀, 默认是 render(file, noParse = false) { this.context.$$views .render(file, noParse) .then(html => { this.response.render(html) }) .catch(err => { this.response.error(err) }) } get jwt() { return { result: this.#auth, sign(data) { let { ttl } = this.context.get('jwt') let { __mix_key__ } = this.request return this.context.$$jwt.sign(data, __mix_key__, ttl) }, verify() { this.#auth = null let token = this.request.header('authorization') let { __mix_key__ } = this.request if (token) { this.#auth = this.context.$$jwt.verify(token, __mix_key__) return this.#auth } } } } // 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) } // 会话读写 session(key, val) { var { enabled } = this.context.get('session') var { ssid } = this.request if (enabled) { if (arguments.length < 2) { // 这里返回的是Promise对象 return this.context.$$session.get(ssid, key) } key += '' this.context.$$session.set(ssid, key, val) } else { throw Error('Session was disabled.') } } //针对框架定制的debug信息输出 xdebug(err) { var msg = err if (this.context.get('debug')) { msg = err.message || err } msg = encodeURIComponent(msg + '') this.response.append('X-debug', msg) } }