UNPKG

@zenweb/controller

Version:

Zenweb Controller module

23 lines (22 loc) 880 B
import path from 'node:path'; import globby from 'globby'; import { debug as _debug } from '@zenweb/core'; import { pathToFileURL } from 'node:url'; export const debug = _debug.extend('controller'); export async function* discoverControllerClass(dir, patterns) { if (dir.startsWith('./')) { dir = path.join(process.cwd(), dir.slice(2)); } for (const file of await globby(patterns || '**/*.{js,ts,jsx,tsx}', { cwd: dir })) { debug('load:', file); const lastDot = Math.max(0, file.lastIndexOf('.')); const filename = lastDot ? file.slice(0, lastDot) : file; const importUrl = pathToFileURL(path.join(dir, file)).href; const mod = await import(importUrl); for (const i of Object.values(mod)) { if (typeof i === 'function') { yield { filename, class: i }; } } } }