UNPKG

@sasonarik/nextapi-swagger

Version:

CLI tool to generate Next.js API routes and types from Swagger/OpenAPI specs

54 lines (49 loc) 1.79 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateHandlerForMethod = generateHandlerForMethod; function generateHandlerForMethod({ method, route, operation, baseName, }) { const hasPathParam = /{[^}]+}/.test(route); const expectsBody = operation.requestBody !== undefined; const summary = operation.summary ? `// ${operation.summary}` : ""; const fetchUrl = route.replace(/{(.*?)}/g, (_, key) => `\$\{${key}\}`); const paramExtract = hasPathParam ? `const url = new URL(request.url);\n const id = url.searchParams.get("id");` : ""; const tokenHeader = `const token = request.headers.get("authorization");`; const bodyParse = expectsBody ? `const body = await request.json();` : ""; const fetchOptions = [ `method: "${method}",`, `headers: {`, ` Authorization: token || "",`, expectsBody ? ` "Content-Type": "application/json",` : "", `},`, expectsBody ? `body: JSON.stringify(body),` : "", ] .filter(Boolean) .join("\n "); return ` import { NextRequest, NextResponse } from "next/server"; import { ${baseName} } from "@/utils/apiBaseUrls"; ${summary} export async function ${method}(request: NextRequest) { try { ${paramExtract} ${tokenHeader} ${bodyParse} const response = await fetch(\`\${${baseName}}${fetchUrl}\`, { ${fetchOptions} }); if (!response.ok) { throw new Error(\`Failed to fetch: \${response.status}\`); } const data = await response.json(); return NextResponse.json(data); } catch (err) { return NextResponse.json( { message: "Error", error: (err as Error).message }, { status: 500 } ); } } `; }