dreamland/scripts/routes.ts
2022-09-14 23:27:01 +02:00

96 lines
No EOL
2.7 KiB
TypeScript

import { join, relative, ensureFileSync } from "../deps.ts";
const ROUTES_FILE = "routes.generated.ts";
interface PageRoute {
path: string;
route: string;
}
async function readDir(dir: URL): Promise<PageRoute[]> {
// Sort the Entries
const entries = [...Deno.readDirSync(dir)]
entries.sort((a, b) => a.name.toUpperCase() < b.name.toUpperCase() ? -1 : 1);
const routes: PageRoute[] = []
for (const file of entries) {
const path = join(dir.pathname, file.name)
if (file.isDirectory) {
const sub = await readDir(new URL(path, import.meta.url))
routes.push(...sub)
continue;
}
const relativePath = relative(
new URL(import.meta.url + "/..").pathname,
path
)
const route = "/" + relativePath.replaceAll(
/\[(.*?)\]/g,
"{$1}",
).replace(/(\.ts)|(\.js)|(\/index(\.ts|\.js))/, "")
.replace(/[\\/]+/g, '/')
const filePath = `./${relativePath}`;
const replaced = route.replace("/../src/routes", "")
let finalRoute = replaced;
if (replaced.includes('index') && !replaced.startsWith("/index"))
finalRoute = replaced.replace("/index", "")
else
finalRoute = replaced.replace('/index', '/')
routes.push({
route: finalRoute,
path: filePath,
});
}
return routes;
}
function createFile(routes: PageRoute[]): string {
let string =
`// This File is Autogenerated by scripts/routes.ts
// Do not edit this File manually
// run \`vr routes\` to regenerate this File
import PageRoute from "../utils/types/PageRoute.ts"
${routes.map((route, index) => (
`import { method as method_${index}, handler as handler_${index} } from "${route.path.replace(/[\\/]+/g, '/')}";`).replace('./../src', ".")).join("\n")}
const routes: PageRoute[] = [\n ${routes.map((route, index) => (`{ method: method_${index}, handler: handler_${index}, route: "${route.route}" }`)).join(",\n ")}
]
export default routes
`
return string
}
async function write(folderwithroutes: string | URL, file: string | URL) {
if (typeof folderwithroutes === "string") folderwithroutes = new URL(folderwithroutes, import.meta.url);
// console.log(folderwithroutes)
const routes = await readDir(folderwithroutes)
const content = createFile(routes)
await Deno.writeTextFile(`./src/${file}`, content)
}
if (import.meta.main) {
console.log(`Writing ${ROUTES_FILE}`)
try {
ensureFileSync(`./src/${ROUTES_FILE}`)
await write('../src/routes', ROUTES_FILE)
} catch (error) {
console.error(error)
Deno.exit(1)
}
console.log(`File written.`)
Deno.exit(0)
}