Home > Article > Web Front-end > Node.js framework ThinkJS development controller explanation
Original: Jingxiu.com web page instant push | Please indicate the source for reprinting
Link:
This series of tutorials is based on ThinkJS v2.x version (official website) Examples are introduced, and the tutorial focuses on practical operations.
This article continues to explain the use of Controller.
If you want to do something when the object is instantiated, the constructor method is the best choice. The constructor provided by ES6 is constructor
.
The constructor method is the default method of the class. This method is automatically called when an object instance is generated through the new command. A class must have a constructor method. If not explicitly defined, an empty constructor method will be added by default.
Method
ECMAScript 6 Getting Started Author: Ruan Yifeng
The power of thinkjs is that we can not only follow the rules The export default class
declares Class by itself, and also provides a method to dynamically create Class: think.controller
.
But the Class dynamically created by thinkjs does not have a constructor
, but provides an init
as an alternative to the constructor method, which is used in the same way as the constructor
Consistent.
The previous article (Node.js Domestic MVC Framework ThinkJS Development Controller Chapter Base Class and Inheritance Chain Part) also has examples of the use of the init
method, look at the code again:
// src/home/controller/base.js'use strict';export default class extends think.controller.base { init(...args) {super.init(...args);// 要求全部 url 必须携带 auth 参数let auth = this.get('auth');if (think.isEmpty(auth)) { return this.error(500, '全部 url 必须携带 auth 参数');} }}
Of course, this does not mean that you cannot use the constructor
method. If you are like me, you are used to using export default class
to declare the Class yourself. You can still use the standard constructor
method.
For the method of dynamically creating Class in thinkjs, please refer to the official documentation and will not be repeated here.
thinkjs has implemented several very useful magic methods, which provides great convenience for development. Manually like ~
As the name suggests, the pre-operation will be executed before the specific Action in the Controller is executed, which means "executed before xxx". Let’s look at the code:
// src/home/controller/user.js'use strict';export default class extends think.controller.base { __before() {console.log('this is __before().'); } indexAction() {console.log('this is indexAction().');return this.end(); }}// 访问 /home/user/index 的执行结果如下:// this is __before().// this is indexAction().
Then someone may say: It seems that __before
has the same purpose as init
. As usual, let’s look at the code:
// src/home/controller/user.js'use strict';export default class extends think.controller.base { init(...args) {super.init(...args);console.log('this is init().'); } __before() {console.log('this is __before().'); } indexAction() {console.log('this is indexAction().');return this.end(); }}// 访问 /home/user/index 的执行结果如下:// this is init().// this is __before().// this is indexAction().
Do you see it? There is still a sequence of execution, here is a more complicated one:
// src/home/controller/base.js'use strict';export default class extends think.controller.base { init(...args) {super.init(...args);console.log('this is base.init().'); }}// src/home/controller/user.js'use strict';export default class extends think.controller.base { init(...args) {super.init(...args);console.log('this is user.init().'); } __before() {console.log('this is user.__before().'); } indexAction() {console.log('this is user.indexAction().');return this.end(); }}// 访问 /home/user/index 的执行结果如下:// this is base.init().// this is user.init().// this is user.__before().// this is user.indexAction().
Okay, you would say "expected"~
After understanding the pre-operation, the post-operation is not difficult to understand. Look at the code:
// src/home/controller/user.js'use strict';export default class extends think.controller.base { init(...args) {super.init(...args);console.log('this is init().'); } __before() {console.log('this is __before().'); } __after() {console.log('this is __after().'); } indexAction() {console.log('this is indexAction().');return this.end(); }}// 访问 /home/user/index 的执行结果如下:// this is init().// this is __before().// this is indexAction().
Eh? Something seems wrong. . . __after
Not executed.
Of course this is not caused by __after
written above indexAction
! Modified code:
// src/home/controller/user.js'use strict';export default class extends think.controller.base { init(...args) {super.init(...args);console.log('this is init().'); } __before() {console.log('this is __before().'); } __after() {console.log('this is __after().');return this.end(); } indexAction() {console.log('this is indexAction().'); }}// 访问 /home/user/index 的执行结果如下:// this is init().// this is __before().// this is indexAction().// this is __after().
This time it’s OK, consistent with the expected results.
I know that you have noticed that the code return this.end()
has been moved from indexAction
to __after
.
this.end()
Internally performs the Node.js HTTP response.end() operation, indicating that the entire response stream is over, so if you want to enable # If ##__after, this code must be run in
__after.
init## Part of #'s responsibilities: used to detect when a Controller is accessed by an Action that is not defined, and __call
will take over the operation.
// src/home/controller/user.js'use strict';export default class extends think.controller.base { init(...args) {super.init(...args);console.log('this is init().'); } __call() {console.log(this.http.action + 'Action is not exists.');return this.end(); } indexAction() {console.log('this is indexAction().');return this.end(); }}// 访问 /home/user/test 的执行结果如下:// this is init().// testAction is not exists.
does not exist, the framework will run __call
for processing, our processing Yes logs the error and ends the response output. The sample code places
in the second-level subclass, usually in the base class, which can control the illegal access processing of all subclasses.
If you want to capture the situation when the Controller does not exist, you need to extend the error class of the framework, which will be described in another article.External calling method
//实例化 home 模块下 user controllerlet instance = think.controller('user', http, 'home');
// src/home/controller/user.js 增加_getPoints() { return 8000;}// src/home/controller/index.jslet instance = think.controller('user', this.http, 'home');let points = instance._getPoints();console.log(points); // 打印:8000instance.indexAction(); // 与直接执行 /home/user/index 是一样的效果instance.testAction(); // 报错 [Error] TypeError: instance.testAction is not a function
At first glance, this method is very close to the running result of
this.redirect (except for the magic method that does not trigger __call
), so what does thinkjs provide with this method? What to use? Let’s look at the code: <p class="sourceCode"><br></p><pre class="sourceCode js">// src/home/controller/util.js&#39;use strict&#39;;export default class extends think.controller.base {
calcGPSDistance(lat, lng){// 计算 GPS 两点直线距离return distance;
}
calcBaiduDistance(lat, lng){// 计算 百度大地坐标 两点直线距离return distance;
}
calcSosoDistance(lat, lng){// 计算 Soso坐标 两点直线距离return distance;
}}</pre><p>这是一个助手 Controller,一个“隐身”的 Controller,从 url 是无法直接访问到的,因为它的所有方法名均没有 Action 后缀。</p>
<p>这个场景下,运行时实例化 Controller 并操作其方法的方式就派上用场了。</p>
<h2>内置 http 对象</h2>
<blockquote><p>控制器在实例化时,会将 http 传递进去。该 http 对象是 ThinkJS 对 req 和 res 重新包装的一个对象,而非 Node.js 内置的 http 对象。<br>Action 里如果想获取该对象,可以通过 this.http 来获取。<br><br><em>thinkjs 官网</em></p></blockquote>
<h2>扩展应用:增加一个 n 秒后自动跳转的过渡页功能</h2>
<p>thinkjs 框架并没有给我们准备这样一个过渡页面的功能,那么我们可以自己实现一个来练练手,上代码:</p>
<p class="sourceCode"><br></p><pre class="sourceCode js">// src/common/controller/complete.js&#39;use strict&#39;;export default class extends think.controller.base {
/** * 显示中转页面 * * 调用方式: * let complete = think.controller(&#39;complete&#39;, this.http, &#39;common&#39;); * return complete.display(&#39;应用新增成功!&#39;, &#39;/&#39;, 5); * * @param msg 提示文字,支持 HTML * @param url 后续自动跳转的目标地址 * @param delay 停留秒数 * @returns {think.Promise} */
display(msg, url=&#39;&#39;, delay=3) {let tpl = &#39;common/complete/200&#39;;let opt = think.extend({}, {type: &#39;base&#39;, file_depr: &#39;_&#39;, content_type: &#39;text/html&#39;});this.fetch(tpl, {}, opt).then(content => { content = content.replace(/COMPLETE_MESSAGE/g, msg); if (url) {content = content.replace(/TARGET_URL/g, url);content = content.replace(/WAIT_SECONDS/g, delay); }; this.type(opt[&#39;content_type&#39;]); return this.end(content);}).catch(function(err){ return this.end(&#39;&#39;);});
}}</pre><p class="sourceCode"><br></p><pre class="sourceCode html"><!-- view/common/complete_200.html --><!DOCTYPE html><html><head><title>正在跳转 - 荆秀网</title></head><body><p class="header"><p class="wrap"><p class="logo"><a href="/"><img src="/static/img/logo.png" alt="XxuYou" width="60"></a></p><p class="headr"> </p></p></p><p class="wrap"><p style="margin-top:20px;height:100px;background:url(/static/img/200.gif) top center no-repeat;"></p><h1>COMPLETE_MESSAGE</h1><p class="error-msg"><pre class="brush:php;toolbar:false">提示:页面将在 <span id="_count">WAIT_SECONDS</span> 秒后重定向到 <a href="TARGET_URL">TARGET_URL</a></pre></p><input type="hidden" id="_target_url" value="TARGET_URL" /><input type="hidden" id="_wait_seconds" value="WAIT_SECONDS" /></p><script type="text/javascript">var thisLoad = function () {var _target_url = document.getElementById('_target_url').value;var _wait_seconds = document.getElementById('_wait_seconds').value;if (_target_url == '') return false;if (/^\d+$/.test(_wait_seconds) == false || _wait_seconds < 1 || _wait_seconds >= 3600) {try {document.location.replace(_target_url);} catch(e) {};} else {thisCount(_wait_seconds);window.setTimeout(function () {try {document.location.replace(_target_url);} catch(e) {};}, _wait_seconds*1000);};return true;};var thisCount = function (cnt) {if (cnt < 0) return false;document.getElementById('_count').innerHTML = cnt;window.setTimeout(function () {thisCount(--cnt);}, 1000);};window.attachEvent ? window.attachEvent('onload', thisLoad) : window.addEventListener('load', thisLoad);</script></body></html></pre><p class="sourceCode"><br></p><pre class="sourceCode js">// Controller 内调用方式indexAction() {
// 业务流程。。。
let complete = think.controller(&#39;complete&#39;, this.http, &#39;common&#39;);
return complete.display(&#39;操作成功!&#39;, &#39;/&#39;, 5);}</pre><p>以上新增的 <code>src/common/controller/complete.js
是一个非侵入式的成功业务处理页面,其内部运行与兄弟 Controller src/common/controller/error.js
类似。
以上新增的 view/common/complete_200.html
则是相关的过渡页面的模版。其中存在三个占位符(分别对应 display 方法的入參):
COMPLETE_MESSAGE 用于操作成功的文字提示内容
TARGET_URL 用于稍后会自动进入的目标 url
WAIT_SECONDS 用于页面过渡时间,单位是秒
实现原理其实非常简单,阅读一下两个新增的代码就能明白。
其实这部分因为太简答,我本来是不想写的。不过考虑到教程的完整性,还是写一下比较好。
REST 的概念介绍这里不再赘述,有兴趣的可以自行搜索。
thinkjs 的官网说到:
自动生成 REST API,而无需写任何的代码。
此言不虚,创建 Controller 时只要增加一个参数(thinkjs controller [name] --rest
),即可生成一个能够操作数据库表的 REST API。
当然操作的约定也还是有的:
GET /ticket #获取ticket列表
GET /ticket/12 #查看某个具体的ticket
POST /ticket #新建一个ticket
PUT /ticket/12 #更新ticket 12
DELETE /ticket/12 #删除ticekt 12
遵从了上述操作约定,的确是可以直接操作数据库表内的数据了。
只是这样的 API 只不过是一个“裸奔”状态的 API,还是不能直接投入使用。因为它不仅要求请求方熟悉所有的数据表结构,还要依赖请求方来维护多表数据之间的关联性,更不用提什么操作路径的映射、字段映射、返回数据的映射等等问题了。
就算 thinkjs 还提供了字段过滤、自定义 GET/POST/PUT/DELETE 方法来进行更多的定制,那么最终的结果很可能是在当前的 API 外面再包裹一层能够提供操作路径映射、鉴权令牌发放和识别、字段映射、关联数据维护等等。
当然作为一个开发框架,thinkjs 确实已经做的够多了,足够优秀了,因此我们还是需要像构建一个应用系统那样去完整构建一个可供实施的 REST API 的生产模型。
The above is the detailed content of Node.js framework ThinkJS development controller explanation. For more information, please follow other related articles on the PHP Chinese website!