-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateRoutes.js
More file actions
56 lines (44 loc) · 2.04 KB
/
generateRoutes.js
File metadata and controls
56 lines (44 loc) · 2.04 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
import fs from 'fs';
import path from 'path';
const apiDir = path.resolve(process.cwd(), 'public/api');
const outputFile = path.resolve(process.cwd(), 'api-routes.js');
function walkDir(dir, baseRoute = '') {
let results = [];
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
const newBaseRoute = path.join(baseRoute, entry.name);
results = results.concat(walkDir(fullPath, newBaseRoute));
} else if (entry.isFile() && entry.name.endsWith('.js')) {
// Create route path, replace backslashes with forward slashes on Windows
const routePath = path.join(baseRoute, entry.name.replace(/\.js$/, '')).replace(/\\/g, '/');
results.push({ filePath: fullPath, routePath });
}
}
return results;
}
function generateRoutes() {
if (!fs.existsSync(apiDir)) {
console.error('API directory not found:', apiDir);
process.exit(1);
}
const files = walkDir(apiDir);
let imports = '';
let routeMapEntries = [];
files.forEach(({ filePath, routePath }, idx) => {
const importName = `route${idx}`;
// Get relative import path from current file (api-routes.js) to the route file
// Note: api-routes.js is at project root, so relative path is from project root
let relativeImportPath = path.relative(path.dirname(outputFile), filePath);
if (!relativeImportPath.startsWith('.')) relativeImportPath = './' + relativeImportPath;
// Normalize path to posix style (slashes) for imports
relativeImportPath = relativeImportPath.replace(/\\/g, '/');
imports += `import * as ${importName} from '${relativeImportPath}';\n`;
routeMapEntries.push(` "${routePath}": ${importName}`);
});
const content = `${imports}\nexport default {\n${routeMapEntries.join(',\n')}\n};\n`;
fs.writeFileSync(outputFile, content, 'utf8');
console.log(`Generated route manifest with ${files.length} routes at ${outputFile}`);
}
generateRoutes();