Unknowingly do node development has been half a time, this period of writing to try to solve some problems, realize a bit of ideas, also encountered some pits. It's time to comb the code and plan for the next job.
at this stage, our node server-side code structure is:
At first glance, it seems that there is no problem, in fact, there are some repetitive code, as well as some non-test modules, code organization is not reasonable. All of these issues need to be addressed.
Let's talk about a few common terms.
Router
The routing module is responsible for distributing the request and transferring the request to the specific controller. A controller is a logic that is processed after each request comes in, and the route defines that the request should go into that controller.
Controller
Controller is a scheduling center that accomplishes a task, does not design specific database operations, and does not make page rendering. It is only responsible for obtaining the existing data, processing, calling the corresponding interface to present the data to the client.
Middleware
We know that the server responds to a client request is generally a serial operation, by the routing module to distribute the request to the specific controller, before distributing to the controller, we can do some processing operations on the data, such as to determine the content-type of the request header The field parses the data well in advance, such as filtering out requests for oversized packets. The modules that accomplish these tasks are generally called middleware, also called Filters!
1. Using the MVC structure to rearrange the code
Before Nodejs development, I wrote some PHP code that was influenced by its code structure. The traditional MVC architecture is clear and easy to understand. Looking at some of the code structure of open source projects, I feel that the server-side code structure still has a lot to learn from. Because the front-end interface is drawn based on canvas, there is no traditional rendering interface operation, and the server only completes some basic curd operations.
1.1 Introducing the Router module
A router is introduced before the controller to distribute the request according to the specific business logic abstraction. express4.x provides a router function that discards the previous practice of mounting a request directly onto a global app object (App.use ("api/a", Controler)). The recommended practice is to hang different business modules on different router objects (app.use ('/api/a ', Webrouter)). Then hang the router on the App object.
//之前的做法 var app = express(); app.post(‘/api1/a‘//推荐做法var//user managervar router = express.Router(); router.post(‘/api1/a‘, ControllerA); app.use(‘/api1‘, router);
1.2 Abstraction of several duplicate checksum operations as filter (middleware)
In some modules that need to verify that a user is logged in, it is necessary to determine whether the user's information hangs on the session object. We can abstract this operation into a filter. When we find that several modules have similar preprocessing operations, they can be abstracted into the form of filters.
1.3 Replacing the OAuth module
Server-side integration of a variety of social account authorization login module, after several months of testing and stabilized, but in different browsers actually there is still inconsistent performance. Given the subsequent maintenance costs of the code, or give up the wheel, Nodejs has a Passport module to solve this problem!
1.4 Replacing the existing model module
Our database uses MongoDB, the existing model module is based on the native drive to encapsulate, need to write some new features when the physical work more, consider abandoning this wheel. When writing a PHP program, I wrote an ORM module that abstracted the operation of the database into a language object. Nodejs has a lot of ORM modules, consider using Mongose or sequelize to accomplish this task.
1.5 Optimizing asynchronous processing
From the contact Nodejs Development, one has to face the problem is how to write the asynchronous processing elegant, concise. There are four ways to choose,
Fibjs. We know that Nodejs is based on asynchronous IO and needs to inject a callback function when calling an asynchronous function to wait for the return. If we were able to implement this process by default, this would solve the callback problem. Fibjs Just can solve this problem. However, fibjs serious module intrusion mode. This means that the original NPM module has to be modified.
third-party asynchronous processing module . Nodejs after these years of development, there are some open source modules to solve asynchronous problems, such as async/eventproxy/step/and so on. These modules address the problem of callback pyramids based on event handling.
Promise. Promise is a very good idea, by encapsulating some small function functions into the Promise function, a complex request actually corresponds to a promise function chain. Simple and elegant code organization, good anomaly capture mechanism are the advantages of promise. One problem with promise, though, is that if a module is written in promise, almost any other module associated with it will have to be replaced by the Promise form.
KOA. KOA actively embrace the ECMA6 standard, its use of CO module implementation, synchronous code to express the asynchronous feelings!
KOA need to rewrite the entire server module, and intend to do it later, so abandon it. Promise involved in a lot of code, no more than the direct use of koa ease of how much so also give up. Plan to choose a compromise way, some lightweight module directly with the callback good, believe that good abstract ability can also solve some problems, more complex asynchronous operation through the third-party asynchronous module to complete, the learning cost is small, take it, he le it!
2. Introduction of the Automated Test Module 1.1 basic test
The importance of testing is self-evident, before in the development process also give some more heavy modules to write some tests, but none of the system, not perfect. The unit test plan uses the Assert plus Shouldjs with Mocha to complete the addition of a mock module, and Mocha can easily generate a code coverage test report. Server-side integration testing can use Superagent to request and validate request results.
1.2 Pre-commit Hook
Each commit triggers a test to dynamically detect the robustness of the code. This will prevent it from happening.
1.3 Lock version
Nodejs ecosystem is very prosperous, many of our projects are open source modules, in order to ensure the stability of the project, to avoid some third-party module bug. Lock the version after the test is stable.
Time Plan
3 days
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Nodejs Service End multiplicity construction plan