-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
84 lines (79 loc) · 2.65 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const jsonpath = require('jsonpath');
const { methods } = require('json2server');
const { join } = require('path');
const { readdirSync, statSync } = require('fs');
const { replace, request, stringify } = methods;
exports.listAllFiles = function listAllFiles(dir, fileFilter, filelist) {
let files = readdirSync(dir);
filelist = filelist || [];
files.forEach(function(file) {
if (statSync(join(dir, file)).isDirectory()) {
filelist = exports.listAllFiles(join(dir, file), fileFilter, filelist);
} else if ((typeof fileFilter === 'function' && fileFilter(file)) ||
(typeof fileFilter === 'string' && file.endsWith(fileFilter))) {
filelist.push(join(dir, file));
}
});
return filelist;
};
/**
* Logger to log the request/command and response
* @param {String} debug the things to debug
* @param {String} header header to print before the log
* @param {Object} data the log data
*/
exports.logger = function logger(test, debug, debugonfail, header, data) {
let toRet = [];
if (debug || debugonfail) {
let qr = [];
let toDebug = false;
((debug ? (debug + ',') : '') + (debugonfail || '')).split(',').forEach((db) => {
if (db.length){
let queryVal = exports.jsonquery(data, db);
if (queryVal !== undefined) {
qr.push([db, queryVal]);
toDebug = true;
}
}
});
if (toDebug) {
toRet = [header, qr];
if (debug || debugonfail) {
test.ARdebuggedFor = (debugonfail && debug) ? 'P' : (debugonfail ? 'F': 'P');
test.ARdebuggedLogs = (test.ARdebuggedLogs || []).concat([toRet]);
}
}
}
return toRet;
};
exports.cropString = function cropString(str, ln = 100) {
const st = stringify(str);
if (st.length > ln) {
return st.substring(0, ln-4) + ' ...';
} else {
return st;
}
};
exports.jsonquery = function jsonquery(data, path) {
let res = data;
if (path.indexOf('LEN()<') === 0) {
return jsonpath.query(data, path.substring(6)).length;
} else if(typeof path === 'string' && path.indexOf('TYPEOF<') === 0) {
return (typeof jsonpath.query(data, path.substring(7))[0]);
} else if (path.indexOf('ARRAY<') === 0) {
return jsonpath.query(data, path.substring(6));
} else if (path.indexOf('<') === 5) {
const count = parseInt(path.substr(0, 5), 10);
if (!isNaN(count)) {
return jsonpath.query(data, path.substring(6), count);
}
}
if (data instanceof Object && typeof path === 'string' && path) {
res = jsonpath.query(data, path, 1);
}
res = (Array.isArray(res) && res.length < 2) ? res[0] : res;
return res;
};
exports.request = request;
exports.replace = replace;
exports.noop = function() { };