As we all know, we mainly provide front-end visualization research and development, including 2D topology visualization, 2D power, industrial configuration visualization, 3D visualization, large screen visualization and so on. It looks something like this:

The so-called visualization, certainly need to have data support, generally speaking, later will be connected with the customer’s data services.

At the beginning of development, however, it is usually the developers themselves who simulate. In many cases, data simulation for a project can take up a lot of time.

The data simulation

I’m sure we all have our own ways. For instance,

  • Write Mock data in code
  • Using request interception
  • Map urls to local files using proxy tools such as Charles

Although the above methods can solve our problems, they also come with some problems. For instance,

  • Dirty code
  • Depending on a particular framework
  • Increasing switching costs
  • Interface data structure reconstruction requires manual update
  • inefficient
  • Can’t gracefully co-edit
  • Nonpersistence

Analog data server

Therefore, we want to build a server that can be configured to simulate data. As we all know mockJS is a powerful data simulation plug-in, the first thing we thought of was to build a server by ourselves and invoke MockJS through configuration to generate simulated data. But a brief reflection, found that the workload is not small.

In the end, this should be the fastest way to do it, given the use of easy-mock. Easy-mock has an online service of its own.

However, it is recommended that you do not use online services for some formal project data, because we used online easy-mock service for a project before. Once the client had to present a demonstration to the leader, we tested all kinds of data before and there was no problem. In the formal demo, I found that the effect did not work. After searching, I found that the online Easy-mock service failed. Sadly, the easy-mock service often fails, but I can understand that it is free and open source.

Therefore, it is advisable to build your own easy-mock service.

Set up the easy-mock server

The following describes how to set up an Easy-mock server. The github address of the easy-Mock server is github.com/easy-mock/e…

In this page (later called official Internet bar), there is a simple introduction on how to set up, but it is in English.

Install nodeJS, Mogondb, and redis

Since easy-mock relies on NodeJS, Mogondb, redis, etc. So you need to install these three. Node.js (v8.x, v10.x not supported) & MongoDB (>= v3.4) & Redis (>= v4.0). (The installation must be carried out in strict accordance with the specified version number, otherwise it may fail to start)

Relevant installation instructions are not described here. believe

Easy installation – a mock

Clone easy-mock locally from git address:

 git clone https://github.com/easy-mock/easy-mock.git
Copy the code

CD to the easy-mock directory and call NPM install to install the appropriate Node module:

cd easy-mock 
npm install
Copy the code

The actual process found that there would be many errors with NPM install, and it was necessary to continuously repair several times before success; Therefore, CNPM install is recommended.

Configuration is easy to mock

As mentioned earlier, easy-mock uses mongodb and Redis, so the most important thing to configure their connection information is to go to the config/default.json file and change the content in the red box below:

Start easy to mock

Start the mongodb and Redis services first, and then under the Easy-Mock project, call NPM run dev to start the Easy-Mock service. Enter the address in the browser to access:

If not registered, directly enter any user name and password to register and log in; Have registered, enter the registered user name and password to log in.

Create a project

Easy-mock allows you to create projects that have a demo project by default. Projects are divided into individual projects and team projects. Team projects can add team members, while individual projects belong to individuals only. As shown below:

Whether it is a team project or an individual project, click the Add button to add a project:

Create the interface

Click the created project to enter the page of the project. On the page, there is a button to create an interface, as shown in the picture below:

To create a data interface, enter the interface name (address) and mock syntax on the left to create random data returned by the interface:

The mock grammar

In the interface area, you can easily mock data. The basic syntax is

The basic grammar

1. The attribute value is a String

‘name | min – Max’ : a string: through repeated string to generate a string, repeat number greater than or equal to the min, less than or equal to Max. ‘name | count’ : a string: through repeated string to generate a string, repetition frequency is equal to the count.

2. The attribute value is Number

‘name | + 1’ : number: the attribute value automatically add 1, the initial value for the number ‘name | min – Max’ : number: generate a greater than or equal to min, an integer less than or equal to Max, the attribute value number is used to determine the type. ‘name | min – Max. Dmin -‘ on3dmax: number: generate a floating point number, the integer part is greater than or equal to less than Max, min, the decimal part dmin to on3dmax digits.

    'the number1 | 1-100.1-10': 1,
    'number2 | 123.1-10': 1,
    'number3 | 123.3': 1,
    'number4 | 123.10': 1.123

// =>
{
    "number1": 12.92."number2": 123.51."number3": 123.777."number4": 123.1231091814}Copy the code
3. The property value is Boolean

The name ‘| 1’ : Boolean: randomly generated a Boolean value, the probability that the value is true is 1/2, the probability of a false value also is 1/2. Value: ‘name | min – Max’ : randomly generated a Boolean value, value is the value of the probability is min / + Max (min), value of! The probability of value is Max over min plus Max.

4. The attribute value is Object

‘name | count’ : object: the object property values in the count a randomly selected attributes’ name | min – Max ‘: object: the object property values in the random min to the Max attribute.

5. The property value is Array Array

The name ‘| 1’ : an array property values randomly selected one element in an array, as the final value. ‘name | + 1’ : array order to select one element in an array property values, as the final value. ‘name | min – Max’ : array by repeating array to generate a new array attribute values, repeat number greater than or equal to the min, less than or equal to Max. ‘name | count’ : array: by repeating array to generate a new array attribute values, repetitions for the count.

6. The attribute value is Function

‘name’: function: Executes the function function and takes its return value as the final property value. The context of the function is the object in which the property ‘name’ resides.

7. The attribute value is the regular expression RegExp

‘Name ‘: regexp: Generates a string that matches the regular expression regexp in reverse. String used to generate custom formatting.

Example 8.

Here’s an example:

{
  "data": {
    'value1|1-3': 0.'value2|1-3': 0.'value3|1-3': 0.'total': function() {
      returnValue1 + this.value2 + this.value3},}} // Return the list {"data|1-10": [{
    'name': '@cname', // Chinese name'id|+1': 88, // The attribute value is automatically incremented by 1, starting with 88'age|18-28': 0, // A random integer between 18 and 28, 0 is used only to determine the type'birthday': '@date("yyyy-MM-dd")'/ / date'city': '@city(true)', // Chinese cities'color': '@color', // Hexadecimal colors'isMale|1': true// Boolean value'isFat|1-2': true, / /trueThe probability of theta is 1/3'brother|1': ['jack'.'jim'], // Randomly select 1 element'sister|+1': ['jack'.'jim'.'lily'], // array selects elements sequentially as the result'friends|2': ['jack'.'jim'], // Repeat the property value twice to generate a new array'func': function() {
      returnthis.name; } {}}]"data": {
    "string|1-10": "★"."string2|3": Painted "u"."number|+1": 202,
    "Number2 | 1-100.1-10": 1,
    "boolean|1": true."regexp": /[a-z][A-Z][0-9]/,
    "absolutePath": "@/string @/user/name"."user": {
      "name": "demo"
    },
    "object|2": {
      "310000": "Shanghai"."320000": Jiangsu Province
    },
    "array|1": ["AMD"]}}Copy the code

The response data

Wouldn’t it be nice if you could dynamically return data based on the parameters passed in? Easy Mock supports handling Request objects. That is, we can use some properties of the Request object to make conditional judgments to achieve responsive data. Includes the following attributes:

  • header
  • method
  • url
  • querystring
  • host
  • hostname
  • query
  • cookies

For example:

{
  success: true,
  data: {
    default: "hah",
    _req: function({
      _req
    }) {
      return _req
    },
    name: function({
      _req
    }) {
      return _req.query.name || this.default
    }
  }
}
Copy the code

Returns the name from the _req object.

Restful

Easy Mock supports interface addresses such as /restful/:id/list or /restful/{id}/list.

The interface agent

Easy Mock supports URL address proxy. For example, enter the address directly:

https://api.m.sohu.com/autonews/pool/?n=%E6%96%B0%E9%97%BB&s=1
Copy the code

Easy to mock the shortcomings

Easy-mock is a handy and powerful tool to use. But it also has disadvantages:

  1. User management is very weak, anyone can log in, there is no good control; If the user authority control requirements are more strict, it is not suitable. 2. The item number is too long and cannot be modified. The interface of analog data will carry the item number. So it’s impossible to remember the address, so you have to log on to the Easy-mock site and copy the address.

If the above two requirements are high, consider modifying the open source code yourself.

In general, using easy-mock can greatly reduce the amount of front-end simulation data.

More excellent content, welcome to pay attention to the public account “ITman Biao Shu”.