Skip to content

Instantly share code, notes, and snippets.

@jacoobes
Created August 8, 2024 18:22
Show Gist options
  • Save jacoobes/ee33616d2aa89641000ec318d173763d to your computer and use it in GitHub Desktop.
Save jacoobes/ee33616d2aa89641000ec318d173763d to your computer and use it in GitHub Desktop.
routebuilder ( i forgot why i meade this)
import { readdir, stat } from 'fs/promises';
import { basename, join, parse, dirname } from 'path';
import assert from 'assert';
export const fmtFileName = (fileName: string) => parse(fileName).name;
export const getfilename = (path: string) => fmtFileName(basename(path));
async function deriveFileInfo(dir: string, file: string) {
const fullPath = join(dir, file);
return { fullPath,
fileStats: await stat(fullPath),
base: basename(file) };
}
function parseWildcardName(filename: string): string | null {
const wildcardMatch = filename.match(/\[(.*?)\]/);
return wildcardMatch ? wildcardMatch[1] : null;
}
export class RouteEntry {
public import_path: string
public filename: string
public parent: string
public wildcardName: string | null;
constructor(public route: string) {
this.import_path = "file:///"+route
this.filename = getfilename(this.route)
this.parent = dirname(this.route);
this.wildcardName = parseWildcardName(this.filename);
}
}
export interface ReadPathsConfig {
dir: string
onDir?: (dir: string) => Promise<boolean>|boolean
onEntry?: (etry: RouteEntry) => RouteEntry
}
export async function* readPaths(
config: ReadPathsConfig
): AsyncGenerator<RouteEntry> {
const files = await readdir(config.dir);
for (const file of files) {
const { fullPath, fileStats } = await deriveFileInfo(config.dir, file);
if (fileStats.isDirectory()) {
if(config.onDir && await config.onDir(fullPath)) {
yield* readPaths({ ...config, dir: fullPath });
} else {
yield* readPaths({ ...config, dir: fullPath });
}
} else {
const nowindowsPath = fullPath.replace(/\\/g, '/');
if(config.onEntry) {
yield config.onEntry(new RouteEntry(nowindowsPath));
} else {
yield new RouteEntry(nowindowsPath);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment