core/lib/controller.js

79 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 控制器基类
* @authors yutent (yutent@doui.cc)
* @date 2016-01-02 23:19:16
*
*/
import Smarty from 'smartyx' //模板引擎
import { sign, verify } from '../module/jwt.js'
const smarty = new Smarty()
export default class Controller {
constructor({ ctx, req, res }) {
this.ctx = ctx
this.name = req.app
this.request = req
this.response = res
this.jwt = {
sign: sign.bind(this),
result: verify.call(this)
}
smarty.config('path', this.ctx.get('VIEWS'))
smarty.config('ext', this.ctx.get('temp_ext'))
smarty.config('cache', !!this.ctx.get('temp_cache'))
this.cookie = this.ctx.ins('cookie')
this.session = this.ctx.ins('session')
}
//定义一个变量类似于smarty把该
assign(key, val) {
key += ''
if (!key) {
return
}
if (val === undefined || val === null) {
val = ''
}
smarty.assign(key, val)
}
//模板渲染, 参数是模板名, 可不带后缀, 默认是 .tpl
render(file, noParse = false) {
smarty
.render(file, noParse)
.then(html => {
this.response.render(html)
})
.catch(err => {
this.response.error(err)
})
}
// 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) {
let msg = err
if (this.ctx.get('debug')) {
msg = err.stack || err
}
this.response.append('X-debug', msg + '')
}
}
一个轻量级的,易学的,拓展性灵活的 nodejs MVC 框架, 5 分钟即可上手。取自"Give me five"之意, 一切就是这么简单
JavaScript 100%