/** * 控制器基类 * @author yutent * @date 2020/09/24 15:45:17 */ export default class Controller { #auth = null // 定义一个模板变量 assign(key, val) { if (this.context.$$views) { if (val === undefined || val === null) { val = '' } key += '' if (key) { this.context.$$views.assign(key, val) } } else { throw new Error('Views module not installed.') } } // 模板渲染, 参数是模板名, 可不带后缀, 默认是 render(file, noParse = false) { if (this.context.$$views) { this.context.$$views .render(file, noParse) .then(html => { this.response.render(html) }) .catch(err => { this.response.error(err) }) } else { throw new Error('Views module not installed.') } } get jwt() { return { result: this.#auth, sign: data => { let { __mix_key__ } = this.request return this.context.$$jwt.sign(data, __mix_key__) }, 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 === 1) { 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) { let { enabled } = this.context.get('session') let { 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.') } } }