controller/index.js

113 lines
2.3 KiB
JavaScript

/**
* 控制器基类
* @author yutent<yutent.io@gmail.com>
* @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: () => {
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
}
}
}
// 定义一个模板变量
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)
}
// 会话读写
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.')
}
}
}
controller
JavaScript 100%