import fs from "fs-extra"; import path from "path"; import ejs from "ejs"; import { logger } from "../utils/logger"; /** * API generator options */ export interface ApiGeneratorOptions { directory?: string; methods?: string; } /** * API generator for creating new API routes */ export class ApiGenerator { /** * Generate a new API route * @param name API route name * @param options API generator options */ async generate(name: string, options: ApiGeneratorOptions): Promise { try { // Set default options const directory = options.directory || "src/app/api"; const methods = options.methods || "GET,POST,PUT,DELETE"; // Create API directory const apiDir = path.resolve(directory, name); await fs.ensureDir(apiDir); // Generate API route file await this.generateApiRouteFile(name, apiDir, methods); logger.success(`API route '${name}' created successfully`); } catch (error) { throw new Error( `Failed to generate API route: ${(error as Error).message}` ); } } /** * Generate API route file * @param name API route name * @param apiDir API directory * @param methods HTTP methods */ private async generateApiRouteFile( name: string, apiDir: string, methods: string ): Promise { try { // Format API route name const apiName = this.formatApiName(name); const fileName = "route"; // Get API route template const templateContent = await this.getApiRouteTemplate(methods); // Process template const content = ejs.render(templateContent, { name: apiName, methods: methods.split(","), }); // Write API route file const filePath = path.join(apiDir, `${fileName}.ts`); await fs.writeFile(filePath, content, "utf8"); } catch (error) { throw new Error( `Failed to generate API route file: ${(error as Error).message}` ); } } /** * Format API route name to camelCase * @param name API route name * @returns Formatted API route name */ private formatApiName(name: string): string { return name .split(/[-_\s]+/) .map((part, index) => { if (index === 0) { return part.toLowerCase(); } return ( part.charAt(0).toUpperCase() + part.slice(1).toLowerCase() ); }) .join(""); } /** * Get API route template based on methods * @param methods HTTP methods * @returns API route template content */ private async getApiRouteTemplate(methods: string): Promise { // Define template parts const imports = `import { NextResponse } from 'next/server'; import { z } from 'zod'; // Define schema for validation const <%= name %>Schema = z.object({ // Define your schema here // Example: // id: z.string(), // name: z.string().min(1).max(100), // email: z.string().email(), }); type <%= name.charAt(0).toUpperCase() + name.slice(1) %> = z.inferSchema>; `; const methodTemplates: Record = { GET: ` export async function GET(request: Request) { try { // Get query parameters const url = new URL(request.url); const id = url.searchParams.get('id'); // Fetch data // Example: // const data = await db.<%= name %>.findMany(); // Return response return NextResponse.json({ message: 'Success', data: [] }); } catch (error) { console.error('Error in GET <%= name %>:', error); return NextResponse.json( { error: 'Internal Server Error' }, { status: 500 } ); } }`, POST: ` export async function POST(request: Request) { try { // Parse request body const body = await request.json(); // Validate request body const result = <%= name %>Schema.safeParse(body); if (!result.success) { return NextResponse.json( { error: result.(error as Error).errors }, { status: 400 } ); } // Create resource // Example: // const created = await db.<%= name %>.create({ data: result.data }); // Return response return NextResponse.json( { message: 'Created successfully', data: result.data }, { status: 201 } ); } catch (error) { console.error('Error in POST <%= name %>:', error); return NextResponse.json( { error: 'Internal Server Error' }, { status: 500 } ); } }`, PUT: ` export async function PUT(request: Request) { try { // Parse request body const body = await request.json(); // Validate request body const result = <%= name %>Schema.safeParse(body); if (!result.success) { return NextResponse.json( { error: result.(error as Error).errors }, { status: 400 } ); } // Update resource // Example: // const updated = await db.<%= name %>.update({ // where: { id: result.data.id }, // data: result.data // }); // Return response return NextResponse.json( { message: 'Updated successfully', data: result.data } ); } catch (error) { console.error('Error in PUT <%= name %>:', error); return NextResponse.json( { error: 'Internal Server Error' }, { status: 500 } ); } }`, DELETE: ` export async function DELETE(request: Request) { try { // Get ID from URL const url = new URL(request.url); const id = url.searchParams.get('id'); if (!id) { return NextResponse.json( { error: 'ID is required' }, { status: 400 } ); } // Delete resource // Example: // await db.<%= name %>.delete({ where: { id } }); // Return response return NextResponse.json( { message: 'Deleted successfully' } ); } catch (error) { console.error('Error in DELETE <%= name %>:', error); return NextResponse.json( { error: 'Internal Server Error' }, { status: 500 } ); } }`, PATCH: ` export async function PATCH(request: Request) { try { // Parse request body const body = await request.json(); // Validate request body const partialSchema = <%= name %>Schema.partial(); const result = partialSchema.safeParse(body); if (!result.success) { return NextResponse.json( { error: result.(error as Error).errors }, { status: 400 } ); } // Update resource partially // Example: // const updated = await db.<%= name %>.update({ // where: { id: result.data.id }, // data: result.data // }); // Return response return NextResponse.json( { message: 'Updated successfully', data: result.data } ); } catch (error) { console.error('Error in PATCH <%= name %>:', error); return NextResponse.json( { error: 'Internal Server Error' }, { status: 500 } ); } }`, }; // Build template based on selected methods const methodsArray = methods.split(","); let template = imports; for (const method of methodsArray) { if (methodTemplates[method]) { template += methodTemplates[method]; } } return template; } }