-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (74 loc) · 2.08 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
const { join, parse, relative, sep } = require("path");
const globby = require("globby");
const express = require("express");
const defaults = {
// rename to filePattern?
pattern: "**/*.js",
};
module.exports = function autoRouter(dir=process.cwd(), options) {
options = {
...defaults,
...options,
};
const pattern = join(dir, options.pattern);
// FIXME: make this async
const filePaths = globby.sync(pattern);
const app = express();
configureApp(app, filePaths);
return app;
async function configureApp(app, filePaths) {
for (const filePath of filePaths) {
const config = {
filePath,
browserPath: toBrowserPath(filePath, dir),
module: require(filePath),
};
app.all(config.browserPath, config.module);
}
}
};
function toBrowserPath(filePath, dir) {
let browserPath = fileSystemToBrowserPath(filePath, dir);
browserPath = toForwardSlashes(browserPath);
browserPath = addRouteParams(browserPath);
browserPath = removeIndexAndExtension(browserPath);
return browserPath;
}
function fileSystemToBrowserPath(filePath, root) {
const pathFromRootDirToFile = relative(root, filePath);
const absoluteBrowserPath = join("/", pathFromRootDirToFile);
return absoluteBrowserPath;
}
// force forward slashes because this is for a browser context
function toForwardSlashes(path) {
return String(path).replace(/\\/g, "/");
}
function removeIndexAndExtension(path) {
const parsed = parse(path);
if (parsed.base === "index.js") {
return join(parsed.dir, "/");
} else {
return join(parsed.dir, parsed.name);
}
}
function addRouteParams(path) {
const parsed = parse(path);
parsed.dir = parsed.dir
.split("/")
.map(withRouteParams)
.join("/");
return unparse(parsed);
}
function unparse(pathObject) {
return join(pathObject.dir, pathObject.base);
}
function withRouteParams(dir) {
const pattern = /\[(?<name>.*)\]/;
const match = pattern.exec(dir);
if (match) {
const { name } = match.groups;
return `:${name}`;
} else {
return dir;
}
}