Home > Web Front-end > JS Tutorial > body text

Thinking and practice of front-end and back-end separation based on NodeJS (3) Lightweight interface configuration modeling framework_node.js

WBOY
Release: 2016-05-16 16:35:21
Original
1140 people have browsed it

Foreword

The development model of using Node to separate the front-end and back-end brings some advantages in performance and development process, but it also faces many challenges. Under Taobao's complex business and technical architecture, the backend must rely on Java to build the infrastructure and provide relevant business interfaces for the frontend to use. One of the most important tasks of Node in the entire environment is to proxy these business interfaces to facilitate the front-end (Node side and browser side) to integrate data for page rendering. How to do a good job in agency work so that after the separation of front-end and back-end development, the process can still be seamlessly connected, is an issue we need to consider. This article will discuss this issue and propose solutions.

Since the interfaces provided by the backend may be diverse, there may also be various ways for developers to access these interfaces when writing Node-side code. If we do not implement a unified architecture in terms of interface access methods and usage, the following problems will arise:

1. Each developer uses their own coding style to write interface access code, causing confusion in the project directory and coding style, making maintenance relatively difficult.
2. Each developer writes his own mock data method. After development, he needs to manually modify the code to remove the mock.
3. Each developer may maintain some configuration files in order to implement different environment switching of the interface (daily, pre-release, online).
4. The data interface calling method cannot be easily reused by various business models.
5. The description of the data interface is scattered in every corner of the code, and may be inconsistent with the interface document agreed by the back-end personnel.
6. After the entire project is developed separately, the cost of joint debugging or test regression of the interface is still very high, and every interface provider and user needs to be involved.
So we hope to have such a framework that uses the mechanism provided by the framework to describe all the external interfaces that the project depends on, manage them uniformly, provide flexible interface modeling and calling methods, and provide a convenient online environment and The production environment switching method enables seamless integration of front-end and back-end development. ModelProxy is a lightweight framework that meets such requirements. It is one of the core components of Midway Framework and can also be used independently. Using ModelProxy can bring the following advantages:

1. Different developers write interface access codes in a unified way, with clear meaning and reduced maintenance difficulty.
2. The factory singleton mode is adopted inside the framework to realize the interface configuration once and reuse multiple times. And developers can customize and assemble their own business models (dependency injection) at will.
3. It is very convenient to switch between online, daily and pre-release environments.
4. Built-in mock engines such as river-mock and mockjs make it very convenient to provide mock data.
5. Use interface configuration files to uniformly manage interface dependency descriptions to avoid being scattered among various codes.
6. Supports browser-side shared Model, which can be used by the browser for front-end data rendering. The entire proxy process is transparent to the browser.
7. The interface configuration file itself is a structured description document, and the river tool collection can be used to automatically generate the document. It can also be used for related automated interface testing, making the entire development process form a closed loop.

ModelProxy working principle diagram and related development process diagram

In the above figure, the developer first needs to write the description of all the dependent back-end interfaces in the project into the interface.json configuration file in the specified json format. If necessary, you need to write a rule file for each interface, which is the interface rules part in the figure. This rule file is used to mock data during the development phase or use the River tool set to verify the interface during the joint debugging phase. The content of the rules file depends on which mock engine is used (such as mockjs, river-mock, etc.). After the configuration is completed, you can create your own business model in the code according to your own needs.

Here is a simple example:

【Example 1】

The first step is to create the interface configuration file interface.json in the project directory, and add the main search interface json definition in it

Copy code The code is as follows:

{
"title": "pad Taobao project data interface collection definition",
"version": "1.0.0",
"engine": "mockjs",
"rulebase": "./interfaceRules/",
"status": "online",
"interfaces": [ {
"name": "Main search interface",
"id": "Search.getItems",
“urls”: {
"online": "http://s.m.taobao.com/client/search.do"
}
} ]
}

Step 2: Create and use the model in code

Copy code The code is as follows:

//Introduce module
var ModelProxy = require( 'modelproxy' );

// Global initialization introduces the interface configuration file (note: the initialization work occurs only once)
ModelProxy.init( './interface.json' );

//Create model. Please refer to the following article for more creation modes
var searchModel = new ModelProxy( {
SearchItems: 'Search.getItems' // Custom method name: Interface ID defined in the configuration file
} );

// Using model, note: the parameters required to call the method are the parameters required by the actual interface.
searchModel.searchItems( { q: 'iphone6' } )
// !Note that the done method must be called to specify the callback function to obtain the data obtained by calling searchItems asynchronously above!
.done( function( data ) {
console.log( data );
} )
.error( function( err ) {
console.log(err);
} );

The feature richness of ModelProxy is that it supports various forms of profiles to create required business models:

Create using interface ID> The generated object will take the word after the last '.' in the ID as the method name

Copy code The code is as follows:

ModelProxy.create( 'Search.getItem' );

Use key-value JSON object> Custom method name: Interface ID

Copy code The code is as follows:

ModelProxy.create( {
GetName: 'Session.getUserName',
GetMyCarts: 'Cart.getCarts'
} );

Use array form> Take the word after the last . as the method name
The generated method call names in the following example are: Cart_getItem, getItem, suggest, getName

Copy code The code is as follows:

ModelProxy.create( [ 'Cart.getItem', 'Search.getItem', 'Search.suggest', 'Session.User.getName' ] );

Prefix form> All interface IDs that satisfy the prefix will be introduced into the object, and the second half will be used as the method name

Copy code The code is as follows:

ModelProxy.create( 'Search.*' );

At the same time, using these Models, you can easily implement merge requests or dependency requests, and do related template rendering

[Example 2] Merge request

Copy code The code is as follows:

var model = new ModelProxy( 'Search.*' );

// Merge request (except for done, the model methods called below are all specified when configuring the interface id)
model.suggest( { q: 'female' } )
.list( { keyword: 'iphone6' } )
.getNav( { key: 'Fashionable Clothing' } )
.done( function( data1, data2, data3 ) {
                 // The order of parameters is consistent with the order of method calling
console.log( data1, data2, data3 );
} );

[Example 3] Dependency request

Copy code The code is as follows:

var model = new ModelProxy( {
GetUser: 'Session.getUser',
GetMyOrderList: 'Order.getOrder'
} );
// Get the user ID first, and then get the order list based on the ID number
model.getUser( { sid: 'fdkaldjfgsakls0322yf8' } )
.done( function( data ) {
      var uid = data.uid;
                   // The second data request depends on the ID number obtained for the first time
This.getMyOrderList( { id: uid } )
            .done( function(data) {
console.log(data);
               } );
} );

In addition, ModelProxy can be used not only on the Node side, but also on the browser side. Just introduce modelproxy-client.js provided by the official package into the page.
[Example 4] Using ModelProxy

on the browser side

Copy code The code is as follows:




At the same time, ModelProxy can be used together with Midway-XTPL, another core component of Midway, to realize full sharing of data, templates, and related rendering processes on the browser and server sides. For detailed tutorials and documentation about ModelProxy, please go to https://github.com/purejs/modelproxy

Summary

ModelProxy exists as a configured lightweight framework, providing friendly interface model assembly and usage, and at the same time well solving the problem of interface usage specifications in the separation of front-end and back-end development models. During the entire project development process, the interface only needs to be defined and described once, and the front-end developers can reference it. At the same time, the River tool is used to automatically generate documents, form a contract with the back-end developers, and do related automated testing, which greatly optimizes the entire Software engineering development process.

[Note] River is the collective name for the front-end and back-end unified interface specifications and related tool collection developed by Alibaba Group

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