1 | 'use strict'
|
2 |
|
3 | class Base {
|
4 | constructor (app, ctx, next) {
|
5 | this.app = app
|
6 | this.ctx = ctx
|
7 | this.res = this.ctx.res
|
8 | this.next = next
|
9 | this.renderType = 'default'
|
10 | this.data = {}
|
11 | this.tpl = 'index'
|
12 | this.result = '{verb}() call result'
|
13 | this.url = 'redirect url'
|
14 |
|
15 | this.global_filter = ['koa-bodyparser']
|
16 | }
|
17 |
|
18 |
|
19 | before () {
|
20 |
|
21 | }
|
22 |
|
23 | alias () {
|
24 | if (this.ctx.request.body) {
|
25 | this.body = this.ctx.request.body
|
26 | }
|
27 |
|
28 | if (this.ctx.request.query) {
|
29 | this.query = this.ctx.request.query
|
30 | }
|
31 |
|
32 |
|
33 |
|
34 | if (this.ctx.params) {
|
35 | this.params = this.ctx.params
|
36 | }
|
37 | }
|
38 |
|
39 | after () {
|
40 |
|
41 | }
|
42 |
|
43 | write () {
|
44 | let write = this.res.write.bind(this.res)
|
45 | write.apply(write, arguments)
|
46 | }
|
47 |
|
48 | end () {
|
49 | this.renderType = 'customEnd'
|
50 | let end = this.res.end.bind(this.res)
|
51 | end.apply(end, arguments)
|
52 | }
|
53 |
|
54 | execute () {
|
55 | let self = this;
|
56 | if (this.renderType === 'default') {
|
57 | return new Promise(function (resolve, reject) {
|
58 | resolve(self.result)
|
59 | })
|
60 | }
|
61 |
|
62 | if (this.renderType === 'view') {
|
63 | var obj = {
|
64 | data: this.data,
|
65 | tpl: this.tpl
|
66 | }
|
67 | Object.assign(obj, this.result)
|
68 |
|
69 | return this.compile(obj.tpl, obj.data).then(function (html) {
|
70 | return new Promise(function (resolve, reject) {
|
71 | resolve(html ? html : self.result)
|
72 | })
|
73 | })
|
74 | }
|
75 |
|
76 |
|
77 | if (this.renderType === 'redirect') {
|
78 | return new Promise(function (resolve, reject) {
|
79 | resolve(true)
|
80 | })
|
81 | }
|
82 |
|
83 |
|
84 | if (this.renderType === 'customEnd') {
|
85 | return new Promise(function (resolve, reject) {
|
86 | resolve(true)
|
87 | })
|
88 | }
|
89 | }
|
90 |
|
91 | redirect (url) {
|
92 | if (url) this.url = url
|
93 |
|
94 | this.renderType === 'redirect'
|
95 | this.ctx.redirect(this.url)
|
96 | }
|
97 | }
|
98 |
|
99 | module.exports = class BaseController extends Base {
|
100 | getTplPath (tpl) {
|
101 | let self = this
|
102 | let viewPath = self.app.opts.root + '/' + self.app.opts.views.path
|
103 | return viewPath + '/' + tpl + '.' + self.app.opts.views.extension
|
104 | }
|
105 |
|
106 | compile (tpl, data) {
|
107 | let self = this
|
108 | return new Promise(function(resolve, reject){
|
109 | resolve(self.result)
|
110 | })
|
111 | }
|
112 |
|
113 | render (tpl, data) {
|
114 | this.renderType = 'view'
|
115 | if (tpl) this.tpl = tpl
|
116 | if (data) this.data = data
|
117 | }
|
118 | } |
\ | No newline at end of file |