Author: Xie Xiaodai

Source:

https://my.oschina.net/xbl/blog/2246297

The copyright of this article belongs to the author


Writing in the front

Have you ever come across:

  • No sooner had the front-end code been written than the back-end interface changed

  • Interface documentation is never right

  • Testing can never begin until close to live

Why do you suffer more than ever when the front and back ends are separated?

The separation of the front and back ends is not news, and there are more problems when it comes to actual separation. To solve the current pain, you need to know the cause of the pain: Why does the interface change so much?

1. I didn’t have a good idea at the beginning of design, which requires improving my ability to understand requirements and interface design.

2. The cost of change is low, as the German saying goes: “Spit in the soup.” Only in this way can people give up the soup and stop unreasonable behavior.

The efficiency is improved when the front and back end students sit together and work together. When the back end students interface changes, they only need to notify verbally. We have no documentation, we are very agile.

Yes, we need to acknowledge that this can be very efficient with development, but frequent changes lead to constant rework, which creates another kind of waste that can be reduced or even eliminated.

Why is interface documentation never correct?

Interface documentation plays a role in defining the interface, but it is useless after the interface is written. Documentation is bound to always lag behind the actual interface as the back interface changes frequently, and maintaining documentation brings costs but no value.

Who will see the document unless the interface is provided externally? What good is it if no one’s looking?

Some companies just throw out the interface documentation and say we’re going to embrace agile. So interface documentation is lagging behind because it doesn’t add value to us.

Why does testing never begin until close to live?

One requirement, back-end development 4 days, front-end development 4 days, coordinated 4 days, test students only have 2 days or even less time, test can only bring bugs online.


Existing development process

In the development stage, the test students can not intervene, the interface is changing, the front end is also changing, before “test” can only drink tea, “test” after the busy.

Automation? Don’t even think about it. If you have a good skill, you can only test it manually after “embracing change”. Occasionally, I have to pull in the front desk girl as a test girl.

Manual testing is tedious, tedious work that is error-prone and cannot be repeated quickly enough to quickly regress to tested functionality.

How to break?

The solution is to get value out of interface documentation, increase the cost of changing interfaces, and get testing involved early.

The value of the interface document is to give meaning to the contract. It is like signing a contract and not changing anyone, so that we are bound to recognize only the contract and not the person.

The contract should be driven by the front end and negotiated by the front end. Because front-end students are in close contact with UX and have a better understanding of the data required by the page and the overall User Journey, front-end students’ drive will be more reasonable.

After the contract is finalized, help us generate the Mock Server (we will introduce a tool later), and the front and back end students will develop independently according to the contract.

Mock Server can temporarily replace background services and help front-end development. Meanwhile, test students can write test scripts according to contract documents and use Mock Server for script verification. The diagram below:


Improved development process

When the back-end interface changes, the contract must be modified in addition to oral notification, and the front-end students and test students can modify separately. This makes it more expensive to modify contracts, makes people more careful about contracts, and encourages us to improve our interface design capabilities.

It is not a mistake to see that there is no “tuning” in the diagram, but rather that “tuning” is no longer a job and you only need to change the configuration of the agent after deployment.

Even modern front-end frameworks (such as Vue or React) can be configured at development time without requiring any code adjustments later.

What about the “test”? Testing is always going on, there is no longer a “test” link, whether the front and back end of either side of the development, testing students can test.

It’s easier said than done. We need tools to help us. There are many tools for interface description. I prefer Raml to Swagger and Raml. As shown below:

The API documentation

It is not enough for the description tool to generate documents, but also to generate Mock Servers. If the description tool and the Mock Server are separate, it adds extra work. Fortunately, it is raml-mocker.

raml-mocker

Raml – mocker (https://github.com/xbl/raml-mocker) is a Mock Server based on raml use Nodejs development tools, Use the example directive that sets response in the Raml description interface

Raml-mocker parses the raml file and launches a Mock Server that returns the contents of Example to the browser.


start

Initialize the project

git clone https://github.com/xbl/raml-mocker-starter.git raml-api
cd raml-api
git remote rm originCopy the code


The installation

yarn
# or
npm installCopy the code

Start the mock server

yarn start
# or
npm startCopy the code
Test the curl -i http://localhost:3000/api/v1/users/1/books/# orCurl -i http://localhost:3000/api/v1/users/1/books/1 API visual documentation yarn run build# orNPM run build This function uses ramL2HTML.Copy the code


Configuration. The raml – config. Json

{
  "controller": "./controller"."raml": "./raml"."main": "api.raml"."port": 3000."plugins": []}Copy the code


  • Controller: Controller directory path, explained in more detail in the advanced section

  • Raml: raml file directory

  • Main: entry file in the raml directory

  • Port: indicates the port number of the mock Server

  • Plugins: plugins

Getting started: Mock Server


Raml-mocker just add example to response:

/books:
  /:id:
    post:
      body:
        application/json:
          type: abc
      responses:
        200:
          body:
            application/json:
              type: song
              # Mock data returned
              example: ! include ./books_200.jsonCopy the code
books_200.json{
  "code": 200.
  "data": [
    {
      "id": 1.
      "title": "books title".
      "description": "books desccription1"
    },
    {
      "id": 2.
      "title": "books title".
      "description": "books desccription2"
    }
  ]
}
through curl Request: curl -i http://localhost:3000/api/v1/users/1/books will get example The only disadvantage is that you cannot dynamically return different data based on the parameters. Don't worry, please look down.Copy the code


Advanced: Dynamic Server


If static Mock data is not enough for your needs, Raml-Mocker also provides dynamic functionality.

Add the (Controller) directive to the RAML document to add dynamic servers, such as:

/books:
  type:
    resourceList:
  get:
    description: Get the user's book
    (controller): user#getBook
    responses:
      200:
        body:
          type: song[]
          example: ! include ./books_200.jsonCopy the code

In the documentation (controller) represents the getBook function in the controller directory user.js.


controller/user.js

exports.getBook = (req, res, webApi) = > {
  console.log(webApi);
  res.send('Hello World! ');
}Copy the code

Raml-mocker is developed on the basis of ExpressJS, reQ and RES can refer to express documents.

WebApi returns the configuration in the document:

{
  "absoluteUri": "/api/:version/users/:user_id/books"."method": "get"."controller": "user#getBook"."responses": [{"code": "200"."body": "... example ..."."mimeType": "application/json"}}]Copy the code


In this way, Raml-Mocker provides more extensible space, and we can even implement some logic in the Controller.

The plug-in

Raml-mocker provides a plug-in mechanism that allows us to process the content of the response without using the Controller directive, for example using Mockjs.

.raml-config.json

{
  "controller": "./controller"."raml": "./raml"."main": "api.raml"."port": 3000."plugins": ["./plugins/mock.js"]}Copy the code


./plugins/mock.js


var { mock } = require('mockjs');

module.exports = (body) = > {
  try {
    return mock(JSON.parse(body));
  } catch(e) {}
  return body;
}
Copy the code


Enjoy it!Copy the code


conclusion

The separation of the front and back ends can make our responsibilities clearer, break the limitation of the front-end play, and improve the development efficiency after the decoupling of the work.

However, because we did not plan the development process well, we did not play its due value, resulting in more waste.

Raml-mocker can help us solve certain problems in tools. More importantly, it is the idea of continuous improvement. Only when the team has the same idea, it is possible to achieve fast delivery.

END

Long press the qr code below to pay immediate attention to [Tanuki technology Nest]

Top technical experts from Alibaba, JD.com, Meituan and Bytedance are in charge

Create a “temperature” technology nest for IT people!