addRouteToController method

Future<Map<String, dynamic>> addRouteToController(
  1. Map<String, dynamic> params
)

Add route to existing controller

Implementation

Future<Map<String, dynamic>> addRouteToController(
  Map<String, dynamic> params,
) async {
  try {
    final controllerPath = params['controllerPath'] as String;
    final httpMethod = params['httpMethod'] as String;
    final path = params['path'] as String;
    final methodName = params['methodName'] as String;
    final returnType = params['returnType'] as String? ?? 'String';

    final fullPath = p.isAbsolute(controllerPath)
        ? controllerPath
        : p.join(projectRoot, controllerPath);

    if (!await FileUtils.fileExists(fullPath)) {
      return {
        'success': false,
        'error': 'Controller file not found: $fullPath',
      };
    }

    // Generate route method
    final methodCode = ControllerTemplate.generateRouteMethod(
      httpMethod: httpMethod,
      path: path,
      methodName: methodName,
      returnType: returnType,
    );

    // Read current content
    final content = await FileUtils.readFile(fullPath);
    final lines = content.split('\n');

    // Find the last method or the closing brace
    int insertIndex = lines.length - 1;
    for (int i = lines.length - 1; i >= 0; i--) {
      if (lines[i].trim() == '}') {
        insertIndex = i;
        break;
      }
    }

    // Insert the new method
    lines.insert(insertIndex, methodCode);

    // Write back
    await FileUtils.writeFile(fullPath, lines.join('\n'));

    return {
      'success': true,
      'message': 'Route added successfully',
      'method': methodName,
      'path': path,
    };
  } catch (e) {
    return {
      'success': false,
      'error': e.toString(),
    };
  }
}