-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (81 loc) · 2.47 KB
/
index.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const fs = require('fs');
/**
*
* @param {string} path - the path to the json file used as database
* @param {boolean} isStatic - define if the file must be statically or dynamically
* @param {object|int} delay - add a fake delay to the request
*/
module.exports = function germaine(path, { isStatic, delay } = {}) {
let database;
// Check that the path is defined
if (typeof path !== 'string') {
throw new Error('germaine error: you must provide the path to the file used as database.');
}
// Check that the path is a string
if (typeof path !== 'string') {
throw new Error('germaine error: the path must be a string.');
}
// Compute delay correctly
delay = typeof delay === 'object'
? delay
: { min: delay || 0, max: delay || 0 };
// Try to read the file a first time
try {
database = JSON.parse(fs.readFileSync(path, 'utf8'));
} catch (err) {
throw new Error(err);
}
return ({ url }, res) => {
if (url.includes('?')) {
url = url.split('?')[0];
}
// If the api should not be static, we must read the file at each call
if (isStatic !== false) {
try {
database = JSON.parse(fs.readFileSync(path, 'utf8'));
} catch (err) {
console.error(err);
res.status(500).json({
error: {
message: 'germaine error : cannot read the file ' + path,
status: 500,
name: 'general error',
},
});
}
}
// This function resolves the right database segment from the url path
const resolveDataFromPath = (string = '') => {
const path = string.split('/');
let res = Object.assign({}, database);
path.map(s => {
res = (res && res[s]
? res[s]
: undefined
);
});
return res;
};
// Get a random number, used to simulated latency
const getRandom = (min, max) => (Math.random() * (max - min) + min);
// Clean the url
url = url.replace(/\/$/, '').replace(/^\/+/g, '');
url = url.substring(url.indexOf('/') + 1);
// Get results from the path
const result = resolveDataFromPath(url);
// Resolve the results
if (result) {
setTimeout(() => {
res.json(result);
}, getRandom(delay.min, delay.max));
} else {
res.status(404).json({
error: {
message: 'Sorry, we didn\'t find this. What\'s it called again? 404?',
status: 404,
name: 'not found',
},
});
}
};
};