forked from zuriby/Faker.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fake.js
63 lines (44 loc) · 1.61 KB
/
fake.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
/*
fake.js - generator method for combining faker methods based on string input
*/
function Fake (faker) {
this.fake = function fake (str) {
// setup default response as empty string
var res = '';
// if incoming str parameter is not provided, return error message
if (typeof str !== 'string' || str.length === 0) {
res = 'string parameter is required!';
return res;
}
// find first matching {{ and }}
var start = str.search('{{');
var end = str.search('}}');
// if no {{ and }} is found, we are done
if (start === -1 && end === -1) {
return str;
}
// console.log('attempting to parse', str);
// extract method name from between the {{ }} that we found
// for example: {{name.firstName}}
var method = str.substr(start + 2, end - start - 2);
method = method.replace('}}', '');
method = method.replace('{{', '');
// console.log('method', method)
// split the method into module and function
var parts = method.split('.');
if (typeof faker[parts[0]] === "undefined") {
throw new Error('Invalid module: ' + parts[0]);
}
if (typeof faker[parts[0]][parts[1]] === "undefined") {
throw new Error('Invalid method: ' + parts[0] + "." + parts[1]);
}
// assign the function from the module.function namespace
var fn = faker[parts[0]][parts[1]];
// replace the found tag with the returned fake value
res = str.replace('{{' + method + '}}', fn());
// return the response recursively until we are done finding all tags
return fake(res);
}
return this;
}
module['exports'] = Fake;