常用语法
createMock(params) {
/**
* @description: 基于params对象生成mock数据
* @param {*} obj
* @return {*}
*/
if (params && params instanceof Array && params.length > 0) {
let _num = Random.natural(1, 10);
let _arr = [];
for (let i = 0; i < _num; i++) {
_arr.push(this.createMock(params[0]));
}
return _arr;
}
let obj = {
...params,
};
let _obj = {};
for (let key in obj) {
// 排除数组的情况
if (obj[key] instanceof Array) {
//设置一个随机数
let _num = Random.natural(1, 10);
let _arr = [];
for (let i = 0; i < _num; i++) {
_arr.push(this.createMock(obj[key][0]));
}
_obj[key] = _arr;
} else if (obj[key] instanceof Object) {
//循环对象并赋值
_obj[key] = this.createMock(obj[key]);
} else {
// 排除code与dessc
if (['code', 'desc'].indexOf(key) < 0) {
// 循环赋予规则
switch (obj[key]) {
case 'string':
_obj[key] = /\w{20,30}/;
break;
case 0:
_obj[key + '|1-100'] = 1;
break;
case 1:
_obj[key + '|0-1'] = 1;
break;
case 2:
_obj[key + '|0-2'] = 1;
break;
case 10:
_obj[key + '|1-10'] = 1;
break;
case 'time':
_obj[key] = '@datetime()';
break;
case 'address':
_obj[
key
] = Random.province()+Random.city()+Random.county();
break;
case 'name':
_obj[key] = Random.cname();
break;
case 'email':
_obj[key] = Random.email();
break;
case 'remark':
_obj[key] = Random.cparagraph();
break;
case 'tel':
_obj[key] = /\d{11}/;
break;
case 'regionCode':
_obj[key] = '500112';
break;
default:
_obj[key]=obj[key];
break
}
}
}
}
return _obj;
}