all repos — stealth-developers @ 039ea63e339048b4103f508452368b3563a04188

src/handlers/common.ts (view raw)

 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
import { exists, readdir } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));

export async function crawlDirectory<T>(
	directory: string,
	processFile: (fileUrl: string) => Promise<T | undefined>,
): Promise<T[]> {
	const items: T[] = [];

	async function crawl(dir: string) {
		if (!(await exists(dir))) return [];

		const files = await readdir(dir, { withFileTypes: true });
		for (const file of files) {
			const path = join(dir, file.name);
			if (file.isDirectory()) {
				await crawl(path);
			} else if (file.name.endsWith(".ts")) {
				const fileUrl = `file://${path}`;
				const item = await processFile(fileUrl);
				if (item) items.push(item);
			}
		}
	}

	await crawl(directory);
	return items;
}

export function getHandlerPath(handlerName: string): string {
	return join(__dirname, "..", handlerName);
}