Node.js framework ThinkJS development controller explanation

巴扎黑
Release: 2017-07-17 16:00:11
Original
2241 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 isconstructor.

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 Theexport default classdeclares Class by itself, and also provides a method to dynamically create Class:think.controller.

But the Class dynamically created by thinkjs does not have aconstructor, but provides aninitas an alternative to the constructor method, which is used in the same way as theconstructorConsistent.

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 theinitmethod, 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 theconstructormethod. If you are like me, you are used to usingexport default classto declare the Class yourself. You can still use the standardconstructormethod.

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__beforehas the same purpose asinit. 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. . .__afterNot executed.

Of course this is not caused by__afterwritten aboveindexAction! 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 codereturn this.end()has been moved fromindexActionto__after.

this.end()Internally performs theNode.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__callwill 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__callfor 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:


// src/home/controller/util.js'use strict';export default class extends think.controller.base { calcGPSDistance(lat, lng){// 计算 GPS 两点直线距离return distance; } calcBaiduDistance(lat, lng){// 计算 百度大地坐标 两点直线距离return distance; } calcSosoDistance(lat, lng){// 计算 Soso坐标 两点直线距离return distance; }}
Copy after login

这是一个助手 Controller,一个“隐身”的 Controller,从 url 是无法直接访问到的,因为它的所有方法名均没有 Action 后缀。

这个场景下,运行时实例化 Controller 并操作其方法的方式就派上用场了。

内置 http 对象

控制器在实例化时,会将 http 传递进去。该 http 对象是 ThinkJS 对 req 和 res 重新包装的一个对象,而非 Node.js 内置的 http 对象。
Action 里如果想获取该对象,可以通过 this.http 来获取。

thinkjs 官网

扩展应用:增加一个 n 秒后自动跳转的过渡页功能

thinkjs 框架并没有给我们准备这样一个过渡页面的功能,那么我们可以自己实现一个来练练手,上代码:


// src/common/controller/complete.js'use strict';export default class extends think.controller.base { /** * 显示中转页面 * * 调用方式: * let complete = think.controller('complete', this.http, 'common'); * return complete.display('应用新增成功!', '/', 5); * * @param msg 提示文字,支持 HTML * @param url 后续自动跳转的目标地址 * @param delay 停留秒数 * @returns {think.Promise} */ display(msg, url='', delay=3) {let tpl = 'common/complete/200';let opt = think.extend({}, {type: 'base', file_depr: '_', content_type: 'text/html'});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['content_type']); return this.end(content);}).catch(function(err){ return this.end('');}); }}
Copy after login


<!-- 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>

Copy after login


// Controller 内调用方式indexAction() { // 业务流程。。。 let complete = think.controller(&#39;complete&#39;, this.http, &#39;common&#39;); return complete.display(&#39;操作成功!&#39;, &#39;/&#39;, 5);}
Copy after login

以上新增的 src/common/controller/complete.js是一个非侵入式的成功业务处理页面,其内部运行与兄弟 Controllersrc/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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!