forked from kiranz/just-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
222 lines (172 loc) · 5.9 KB
/
utils.js
File metadata and controls
222 lines (172 loc) · 5.9 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import path from 'path';
import fs from 'fs';
import glob from 'glob';
import he from 'he';
import { customError } from './errors';
import isEqual from 'lodash/isEqual';
export function doesDirectoryExist(dirPath) {
const fullPath = path.resolve(process.cwd(), dirPath);
try {
const stat = fs.statSync(fullPath);
return stat.isDirectory();
} catch (err) {
return false;
}
}
export function findSuiteFiles(basePath, digDeep = false, extensions = ['yml', 'yaml']) {
let files = [];
if (!fs.existsSync(basePath)) {
if (fs.existsSync(basePath + '.yml')) {
basePath += '.yml';
} else if (fs.existsSync(basePath + '.yaml')) {
basePath += '.yaml';
} else {
files = glob.sync(basePath);
if (!files.length) {
throw new Error(`No suites found using path/pattern ${basePath}`);
}
return files;
}
}
try {
let stat = fs.statSync(basePath);
if (stat.isFile()) {
return basePath;
}
} catch (err) {
return;
}
fs.readdirSync(basePath).forEach(function (fileOrDir) {
let file = path.join(basePath, fileOrDir);
try {
var stat = fs.statSync(file);
if (stat.isDirectory()) {
if (digDeep) {
files = files.concat(findSuiteFiles(file, digDeep, extensions));
}
return;
}
} catch (err) {
return;
}
let re = new RegExp('\\.(?:' + extensions.join('|') + ')$');
if (!stat.isFile() || !re.test(file) || path.basename(file)[0] === '.') {
return;
}
files.push(file);
});
return files;
}
export function assertFileValidity(relativeFilePath, fileContext) {
const absPath = path.resolve(process.cwd(), relativeFilePath);
if (!fs.existsSync(absPath)) {
const FileDoesNotExistError = customError('FileDoesNotExistError');
throw new FileDoesNotExistError(`${fileContext} file doesn't exist at '${relativeFilePath}'`);
}
if (!fs.statSync(absPath).isFile()) {
throw new Error(`${fileContext} at: ${relativeFilePath} is not a file`);
}
return absPath;
}
export function loadModule(modulePath) {
try {
return require(modulePath);
} catch (e) {
throw e;
}
}
export async function runModuleFunction(module, fnName, context, args) {
let CustomFunctionNotFoundInModuleError = customError('CustomFunctionNotFoundInModuleError');
let NotAFunctionError = customError('NotAFunctionError');
try {
let func = module[fnName];
if (!func) {
throw new CustomFunctionNotFoundInModuleError(`'${fnName}' function not found in module`);
}
if (typeof func !== 'function') {
throw new NotAFunctionError(`'${fnName}', Provide valid javascript function`);
}
let result = await module[fnName].call(context);
return result;
} catch (error) {
throw error;
}
}
export async function runInlineFunction(fn, context, args) {
let NotAFunctionError = customError('NotAFunctionError');
if (typeof fn !== 'function') {
throw new NotAFunctionError(`'${fn}' is not a function, Provide valid inline javascript function`);
}
try {
let result = await fn.call(context);
return result;
} catch (error) {
throw error;
}
}
export function convertMillisToHumanReadableFormat(duration) {
let milliseconds = parseInt((duration % 1000));
let seconds = parseInt((duration / 1000) % 60);
let minutes = parseInt((duration / (1000 * 60)) % 60);
let hours = parseInt((duration / (1000 * 60 * 60)) % 24);
if (hours === 0) {
return minutes + "m" + seconds + "s." + milliseconds + "ms";
}
return hours + "h" + minutes + "m" + seconds + "s." + milliseconds + "ms";
}
export async function wait(durationInMillis) {
return new Promise(resolve => setTimeout(resolve, durationInMillis));
}
export function isNumber(number) {
return !isNaN(parseFloat(number)) && isFinite(number);
}
export function escapeHTML(html) {
return he.escape(String(html));
}
export function prettifyRequestLog(reqResInfo) {
let result = '';
const request = reqResInfo.request;
const response = reqResInfo.response;
const error = reqResInfo.error;
result += 'Request: \n\n';
result += `${request.method.toUpperCase()} ${request.uri} \n`;
for (let headerKey in request.headers) {
result += `${headerKey}: ${request.headers[headerKey]}\n`;
}
result += '\n';
if (request.body && request.formRequest) {
result += "It's a form/multipart-form request, this may or may not be the actual raw body \n";
result += JSON.stringify(request.body) + '\n';
}
if (request.body && !request.formRequest) {
result += request.body + '\n';
}
if (error) {
result += '\n--Encountered following error \n\n';
result += `${error}`;
result += '\n';
} else {
result += '\nResponse: \n\n';
result += `Status code: ${response.statusCode} \n`;
for (let headerKey in response.headers) {
result += `${headerKey}: ${response.headers[headerKey]}\n`;
}
result += '\n';
if (response.headers['content-type'].includes('application/json')) {
try {
//TODO send json as pretty multiline string so it's easy to read
result += response.body.toString();
} catch (e) {
result += response.body.toString();
}
} else {
result += response.body.toString();
}
result += '\n';
result += `\nRequest duration: ${response.timings.total}ms \n`;
}
return result;
}
export function equals(value, other) {
return isEqual(value, other);
}