Home > Web Front-end > JS Tutorial > Node.js framework ThinkJS development controller explanation

Node.js framework ThinkJS development controller explanation

巴扎黑
Release: 2017-07-17 16:00:11
Original
2348 people have browsed it

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.

Constructor method

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

init and constructor

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 参数');}
  }}
Copy after login

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.

Magic method

thinkjs has implemented several very useful magic methods, which provides great convenience for development. Manually like ~

__before pre- Operation

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().
Copy after login

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().
Copy after login

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().
Copy after login

Okay, you would say "expected"~

__after Operation

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().
Copy after login

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().
Copy after login

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.

__call No operation

This magic method is a bit special. It is not used to run at a certain process node like the previous two magic methods, but it is shared with

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.
Copy after login

You can see that when the accessed

testAction

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

__call

in the second-level subclass, usually in the base class, which can control the illegal access processing of all subclasses.

Tip: This method can only be used to capture the situation when the Action does not exist, but if the Controller does not exist, it will directly trigger a 404 error (taken over by the framework) and cannot interfere.
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

The thinkjs official website API has an interface for instantiating another Controller, but it does not explain the specific use of this:

//实例化 home 模块下 user controllerlet instance = think.controller('user', http, 'home');
Copy after login

Then usually this method can be used to instantiate a sibling-level Controller, or obtain data, or trigger a business process, etc. Let’s look at the code:

// 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
Copy after login

It can be seen that thinkjs provides a way to instantiate a Controller on demand and run its methods.

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><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="sourceCode js">// src/home/controller/util.js&amp;#39;use strict&amp;#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><div class="contentsignin">Copy after login</div></div><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><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="sourceCode js">// src/common/controller/complete.js&amp;#39;use strict&amp;#39;;export default class extends think.controller.base { /** * 显示中转页面 * * 调用方式: * let complete = think.controller(&amp;#39;complete&amp;#39;, this.http, &amp;#39;common&amp;#39;); * return complete.display(&amp;#39;应用新增成功!&amp;#39;, &amp;#39;/&amp;#39;, 5); * * @param msg 提示文字,支持 HTML * @param url 后续自动跳转的目标地址 * @param delay 停留秒数 * @returns {think.Promise} */ display(msg, url=&amp;#39;&amp;#39;, delay=3) {let tpl = &amp;#39;common/complete/200&amp;#39;;let opt = think.extend({}, {type: &amp;#39;base&amp;#39;, file_depr: &amp;#39;_&amp;#39;, content_type: &amp;#39;text/html&amp;#39;});this.fetch(tpl, {}, opt).then(content =&gt; { 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[&amp;#39;content_type&amp;#39;]); return this.end(content);}).catch(function(err){ return this.end(&amp;#39;&amp;#39;);}); }}</pre><div class="contentsignin">Copy after login</div></div><p class="sourceCode"><br/></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="sourceCode html">&lt;!-- view/common/complete_200.html --&gt;&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;title&gt;正在跳转 - 荆秀网&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;p class=&quot;header&quot;&gt;&lt;p class=&quot;wrap&quot;&gt;&lt;p class=&quot;logo&quot;&gt;&lt;a href=&quot;/&quot;&gt;&lt;img src=&quot;/static/img/logo.png&quot; alt=&quot;XxuYou&quot; width=&quot;60&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;p class=&quot;headr&quot;&gt; &lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;p class=&quot;wrap&quot;&gt;&lt;p style=&quot;margin-top:20px;height:100px;background:url(/static/img/200.gif) top center no-repeat;&quot;&gt;&lt;/p&gt;&lt;h1&gt;COMPLETE_MESSAGE&lt;/h1&gt;&lt;p class=&quot;error-msg&quot;&gt;&lt;pre class=&quot;brush:php;toolbar:false&quot;&gt;提示:页面将在 &lt;span id=&quot;_count&quot;&gt;WAIT_SECONDS&lt;/span&gt; 秒后重定向到 &lt;a href=&quot;TARGET_URL&quot;&gt;TARGET_URL&lt;/a&gt;</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(&#39;_target_url&#39;).value;var _wait_seconds = document.getElementById(&#39;_wait_seconds&#39;).value;if (_target_url == &#39;&#39;) 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(&#39;_count&#39;).innerHTML = cnt;window.setTimeout(function () {thisCount(--cnt);}, 1000);};window.attachEvent ? window.attachEvent(&#39;onload&#39;, thisLoad) : window.addEventListener(&#39;load&#39;, thisLoad);</script></body></html></pre><div class="contentsignin">Copy after login</div></div><p class="sourceCode"><br/></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="sourceCode js">// Controller 内调用方式indexAction() { // 业务流程。。。 let complete = think.controller(&amp;#39;complete&amp;#39;, this.http, &amp;#39;common&amp;#39;); return complete.display(&amp;#39;操作成功!&amp;#39;, &amp;#39;/&amp;#39;, 5);}</pre><div class="contentsignin">Copy after login</div></div><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 API

其实这部分因为太简答,我本来是不想写的。不过考虑到教程的完整性,还是写一下比较好。

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template