-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkoala.js
73 lines (52 loc) · 1.84 KB
/
koala.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
import fs from 'fs';
class Koala {
constructor() {
this.routes = {};
this.rootDataDir = '';
this.apiPath = '';
console.log("making new koala... \n");
}
getRoutes(dir, path, content) {
const relativeDir = (dir !== this.rootDataDir) ? dir.replace(this.rootDataDir, '') : '';
path = path ? path + '/' + relativeDir : relativeDir;
content = content || [];
const files = fs.readdirSync(dir);
files.forEach((filename) => {
const absPath = dir + '/' + filename;
let tmp, name;
if (fs.statSync(absPath).isDirectory()) {
this.getRoutes(absPath, path, content);
} else {
tmp = filename.split('.');
tmp.pop(); // remove extension
name = tmp.join('');
this.routes[this.apiPath + path + '/' + name] = absPath;
}
});
return this.routes
};
injectRoutes(router, routes) {
for (const route in routes) {
let handler = (request, response) => {
const filename = routes[request.path];
console.log('GET '+ request.path +' -> '+ filename);
const json = JSON.parse(fs.readFileSync(filename, 'utf8'));
response.json(json);
};
// TODO: expose configuration for which routes are POST
if (route.match(/auth/)) {
router.post(route, handler);
} else {
router.get(route, handler);
}
}
}
attach(router, dataDir, apiPath) {
this.rootDataDir = dataDir;
this.apiPath = apiPath;
const routes = this.getRoutes(dataDir);
console.log("attach routes: ", routes);
this.injectRoutes(router, routes);
}
}
export default Koala;