2017-08-31 18:04:45 +08:00
|
|
|
var strRegex = /\${([a-zA-Z0-9_\.]+)\}/g;
|
|
|
|
var varSplit = '.';
|
|
|
|
var mockSplit = '|';
|
2017-08-30 14:43:44 +08:00
|
|
|
|
|
|
|
function mock(mockJSON, context) {
|
2017-09-03 10:08:39 +08:00
|
|
|
context = context || {};
|
|
|
|
var filtersMap = {
|
|
|
|
regexp: handleRegexp
|
|
|
|
};
|
2017-08-30 14:43:44 +08:00
|
|
|
|
2017-09-03 10:08:39 +08:00
|
|
|
return parse(mockJSON);
|
2017-08-31 18:04:45 +08:00
|
|
|
|
2017-09-03 10:08:39 +08:00
|
|
|
function parse(p, c) {
|
|
|
|
c = c || {};
|
|
|
|
for (var i in p) {
|
|
|
|
if (!p.hasOwnProperty(i)) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (typeof p[i] === 'object') {
|
|
|
|
c[i] = (p[i].constructor === Array) ? [] : {};
|
|
|
|
parse(p[i], c[i]);
|
|
|
|
} else {
|
|
|
|
p[i] = handleStr(p[i]);
|
|
|
|
var filters = i.split(mockSplit), newFilters = [].concat(filters);
|
|
|
|
c[i] = p[i];
|
|
|
|
if (filters.length > 1) {
|
|
|
|
for (var f = 1, l = filters.length, index; f < l; f++) {
|
|
|
|
if (filters[f] in filtersMap) {
|
|
|
|
if ((index = newFilters.indexOf(filters[f])) !== -1) {
|
|
|
|
newFilters.splice(index, 1);
|
|
|
|
}
|
|
|
|
delete c[i];
|
|
|
|
c[newFilters.join(mockSplit)] = filtersMap[filters[f]].call(p, p[i]);
|
2017-08-30 14:43:44 +08:00
|
|
|
}
|
2017-09-03 10:08:39 +08:00
|
|
|
}
|
2017-08-30 14:43:44 +08:00
|
|
|
}
|
2017-09-03 10:08:39 +08:00
|
|
|
}
|
2017-08-30 14:43:44 +08:00
|
|
|
}
|
2017-09-03 10:08:39 +08:00
|
|
|
return c;
|
|
|
|
}
|
2017-08-30 14:43:44 +08:00
|
|
|
|
2017-09-03 10:08:39 +08:00
|
|
|
function handleRegexp(item) {
|
|
|
|
return new RegExp(item);
|
|
|
|
}
|
2017-08-31 18:04:45 +08:00
|
|
|
|
2017-09-03 10:08:39 +08:00
|
|
|
function handleStr(str) {
|
|
|
|
if (typeof str !== 'string' || str.indexOf('{') === -1 || str.indexOf('}') === -1 || str.indexOf('$') === -1) {
|
|
|
|
return str;
|
2017-08-31 18:04:45 +08:00
|
|
|
}
|
2017-09-03 10:08:39 +08:00
|
|
|
str = str.replace(strRegex, function (matchs, name) {
|
|
|
|
var names = name.split(varSplit);
|
|
|
|
var data = context;
|
|
|
|
names.forEach(function (n) {
|
|
|
|
if (data === '') return '';
|
|
|
|
if (n in data) {
|
|
|
|
data = data[n];
|
|
|
|
} else {
|
|
|
|
data = '';
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return data;
|
|
|
|
});
|
|
|
|
return str;
|
|
|
|
}
|
2017-08-30 14:43:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = mock;
|