Skip to content

Commit 501814d

Browse files
committed
refactor: transpile with middleware detector
1 parent b926ebe commit 501814d

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/core/next.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from "node:fs/promises";
22
import path from "node:path";
33
import { directoryExists } from "./dir";
4+
import { detectMiddlewareName } from "./middleware";
45
import { transpile } from "./transpile";
56
import type { OperationObject } from "@omer-x/openapi-types/operation";
67

@@ -33,11 +34,18 @@ function safeEval(code: string, routePath: string) {
3334
}
3435

3536
export async function getRouteExports(routePath: string, routeDefinerName: string, schemas: Record<string, unknown>) {
36-
const content = await fs.readFile(routePath, "utf-8");
37-
const code = transpile(content, routeDefinerName);
37+
const rawCode = await fs.readFile(routePath, "utf-8");
38+
const middlewareName = detectMiddlewareName(rawCode);
39+
const code = transpile(rawCode, routeDefinerName, middlewareName);
3840
const fixedCode = Object.keys(schemas).reduce(injectSchemas, code);
3941
(global as Record<string, unknown>).schemas = schemas;
42+
if (middlewareName) {
43+
// (global as Record<string, unknown>)[middlewareName] = () => { /* mock */ };
44+
}
4045
const result = safeEval(fixedCode, routePath);
4146
delete (global as Record<string, unknown>).schemas;
47+
if (middlewareName) {
48+
// delete (global as Record<string, unknown>)[middlewareName];
49+
}
4250
return result as Record<string, { apiData?: OperationObject } | undefined>;
4351
}

src/core/transpile.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,16 @@ function fixExports(code: string) {
1111
return `${exportFixer1}\n${code}\n${exportFixer2}`;
1212
}
1313

14-
export function transpile(rawCode: string, routeDefinerName: string) {
14+
function injectMiddlewareFixer(middlewareName: string) {
15+
return `const ${middlewareName} = (handler) => handler;`;
16+
}
17+
18+
export function transpile(rawCode: string, routeDefinerName: string, middlewareName: string | null) {
1519
const code = fixExports(removeImports(rawCode));
1620
const parts = [
1721
`import ${routeDefinerName} from '@omer-x/next-openapi-route-handler';`,
1822
"import z from 'zod';",
23+
middlewareName ? injectMiddlewareFixer(middlewareName) : "",
1924
code,
2025
];
2126
return tsTranspile(parts.join("\n"));

0 commit comments

Comments
 (0)