Question
In the daily process of docking with the back-end interface, it is often encountered that the interface field has a null value, such as

{
   code:0,
   msg:'success',
   result:null
}

At this time, when we get result.userInfo again, JavaScript will report an error. Therefore, the front-end not only checks whether the interface status code is 0, but also checks whether the result is the expected object type.
That is from the original

if (res.data.code === 0)

To

if (res.data.code === 0&&res.data.result)

Especially when we expect the data structure to be

{
  code:0,
  result:{
    userInfo:{
      userName:''
    }
  }
}

In order to obtain the value of userName smoothly, we need to make three judgments

let userName = ''
if (res.data.result&&res.data.result.userInfo&&res.data.result.userInfo.userName)
 userName = res.data.result.userInfo.userName

Very headache
And 98% of the backends are not willing to return according to the predetermined data structure
That is to cause object/string/number/array to be null
In time you finally defeated the backend and agreed to return in accordance with the format,
But after all, the interface returns untrusted

So I envisioned a solution mainly to solve so many if judgments and format the interface return as we want.

By retaining the basic format, and then returning the interface to merge into the basic data

The advantage of this is

  1. The expected data structure is completely retained
  2. When debugging the code, you can clearly and intuitively see the data format returned by the current interface to enhance readability
  3. Convenient to do interface mock expansion

zuank
203 声望10 粉丝