also looking at this
chore: wip stx improvements
#1649
241 files
+19022
-1323
| @@ -0,0 +1,83 @@ | ||
| 1 | import type { ApiRoute, HttpMethod } from './types' | |
| 2 | import { existsSync, readdirSync, statSync } from 'node:fs' | |
| 3 | import { join, relative } from 'node:path' | |
| 4 | ||
| 5 | const HTTP_METHODS: HttpMethod[] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] | |
| 6 | ||
| 7 | /** | |
| 8 | * Convert a file path to an API route path. | |
| 9 | * Examples: | |
| 10 | * api/posts/[id].ts -> /api/posts/:id | |
| 11 | * api/users.ts -> /api/users | |
| 12 | * api/posts/[id]/comments.ts -> /api/posts/:id/comments | |
| 13 | */ | |
| 14 | export function filePathToRoutePath(filePath: string, prefix = '/api'): string { | |
| 15 | let route = filePath | |
| 16 | .replace(/\.(ts|js)$/, '') | |
| 17 | .replace(/\/index$/, '') | |
| 18 | ||
| 19 | // Convert [param] to :param | |
| 20 | route = route.replace(/\[([^\]]+)\]/g, ':$1') | |
| 21 | ||
| 22 | // Normalize slashes | |
| 23 | route = `/${route}`.replace(/\/+/g, '/') | |
| 24 | ||
| 25 | // Prepend prefix if the route doesn't already start with it | |
| 26 | if (prefix && !route.startsWith(prefix)) { | |
| 27 | route = `${prefix}${route}` | |
| 28 | } | |
| 29 | ||
| 30 | return route | |
| 31 | } | |
| 32 | ||
| 33 | function collectFiles(dir: string, base: string): string[] { | |
| 34 | const files: string[] = [] | |
| 35 | ||
| 36 | if (!existsSync(dir)) | |
| 37 | return files | |
| 38 | ||
| 39 | const entries = readdirSync(dir) | |
| 40 | for (const entry of entries) { | |
| 41 | const fullPath = join(dir, entry) | |
| 42 | const stat = statSync(fullPath) | |
| 43 | ||
| 44 | if (stat.isDirectory()) { | |
| 45 | files.push(...collectFiles(fullPath, base)) | |
| 46 | } | |
| 47 | else if (entry.endsWith('.ts') || entry.endsWith('.js')) { | |
| 48 | files.push(fullPath) | |
| 49 | } | |
| 50 | } | |
| 51 | ||
| 52 | return files | |
| 53 | } | |
| 54 | ||
| 55 | export async function scanApiRoutes(apiDir: string, prefix = '/api'): Promise<ApiRoute[]> { | |
| 56 | const routes: ApiRoute[] = [] | |
| 57 | const files = collectFiles(apiDir, apiDir) | |
| 58 | ||
| 59 | for (const filePath of files) { | |
| 60 | const relativePath = relative(apiDir, filePath) | |
| 61 | const routePath = filePathToRoutePath(relativePath, prefix) | |
| 62 | ||
| 63 | try { | |
| 64 | const mod = await import(filePath) | |
| 65 | ||
| 66 | for (const method of HTTP_METHODS) { | |
| 67 | if (mod[method]) { | |
| 68 | routes.push({ | |
| 69 | path: routePath, | |
| 70 | method, | |
| 71 | handler: mod[method], | |
| 72 | filePath, | |
| 73 | }) | |
| 74 | } | |
| 75 | } | |
| 76 | } | |
| 77 | catch { | |
| 78 | // Skip files that can't be imported | |
| 79 | } | |
| 80 | } | |
| 81 | ||
| 82 | return routes | |
| 83 | } | |