-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathController.js
More file actions
101 lines (94 loc) · 2.59 KB
/
Controller.js
File metadata and controls
101 lines (94 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const pug = require('pug');
const path = require('path');
const Route = require('./Route');
const { appRoot } = require('./utils');
global.require = require;
const pugCompileOptions = {
cache: true,
doctype: 'html'
}
const viewKey = Symbol('#view');
const rewriteControllerKey = Symbol('#rewriteControllerKey');
module.exports = class Controller {
$beforeAction(){}
$afterAction(){}
constructor({ctx, route, router, view, rewriteController}){
Object.defineProperties(this, {
ctx: { value: ctx },
route: { value: route },
router: { value: router }
});
this[viewKey] = view;
this[rewriteControllerKey] = rewriteController;
}
isRewrite(){
return !!this[rewriteControllerKey];
}
get rewriteController(){
return this[rewriteControllerKey];
}
get request(){
return this.ctx.request;
}
get response(){
return this.ctx.response;
}
get session(){
return this.ctx.session;
}
set session(s){
this.ctx.session = s;
}
get sessionId(){
return this.ctx.sessionId;
}
get cookies(){
return this.ctx.cookies;
}
get query(){
return this.ctx.query;
}
throw(...arg){
this.ctx.throw(...arg);
}
isAjax(){
return this.ctx.headers['x-requested-with'] === 'XMLHttpRequest'
}
renderStream(stream){
this.ctx.body = stream;
}
renderString(string){
this.ctx.body = string;
}
render(model = {}, view){
const controller = this.route.controller;
view = view || this.route.action;
const viewPath = view.startsWith('/') ?
path.join(appRoot, `${view}.pug`) :
path.join(this.route.viewsRoot, `${controller}/${view}.pug`);
this.ctx.body = pug.compileFile(viewPath, pugCompileOptions)({
model,
view: this[viewKey]
});
}
renderJSON(json = {}){
this.ctx.body = json;
}
renderSVG(svg){
this.ctx.body = svg;
this.ctx.type="image/svg+xml";
}
redirect(params, area){
const url = (typeof params === 'string') ? params : this.router.resolve(params, area);
this.ctx.redirect(url);
}
async rewrite(params, area){
const route = (typeof params === 'string') ? this.router.match(params) : new Route(params, area);
const actionTrigger = new (require('./ActionTrigger'))({
ctx: this.ctx,
route,
router: this.router
});
await actionTrigger.trigger(this);
}
}