/** * 控制器基类 * @author yutent * @date 2020/09/24 15:45:17 */ export default class Controller { #auth = null get method() { return this.request.method } get host() { return this.request.host } get hostname() { return this.request.hostname } get ua() { return this.request.headers['user-agent'] } get jwt() { return { result: this.#auth, sign: data => { let { __mix_key__ } = this.request return this.context.$$jwt.sign(data, __mix_key__) }, verify: token => { this.#auth = null let { __mix_key__ } = this.request token ??= this.request.header('authorization') if (token) { this.#auth = this.context.$$jwt.verify(token, __mix_key__) } return this.#auth } } } // 定义一个模板变量 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.') } } // 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) } // 会话读写, 返回的是Promise对象 session(key, val) { let { ssid } = this.request if (this.context.$$session) { key += '' if (arguments.length < 2) { // 这里返回的是Promise对象 return this.context.$$session.get(ssid, key) } this.context.$$session.set(ssid, key, val) } else { throw new Error('Session was disabled.') } } }