fromElement static method

ServerLifecycleComponentMethod? fromElement(
  1. MethodElement object
)

Implementation

static ServerLifecycleComponentMethod? fromElement(MethodElement object) {
  final name = object.name;

  final returnTypeAlias = object.returnType.alias?.element.name;
  String returnType;
  var isFuture = false;
  String? exceptionType;

  final importPaths = <String>{};

  // TODO(mrgnhnt): Handle Future<ALIAS> return types
  if (returnTypeAlias != null && aliasReturnTypes.contains(returnTypeAlias)) {
    returnType = returnTypeAlias;
  } else if (object.returnType case final InterfaceType type
      when type.isAnyFuture) {
    isFuture = true;
    final typeArg = type.typeArguments.first;

    final resolveReturnType = typeArg.getDisplayString();

    returnType = switch (typeArg) {
      InterfaceType() => typeArg.alias?.element.name ?? resolveReturnType,
      _ => resolveReturnType,
    };

    if (returnType.startsWith((ExceptionCatcherResult).name)) {
      throw ArgumentError('Exception types cannot be a Future type');
    }
  } else {
    returnType = object.returnType.getDisplayString();

    if (object.returnType case final InterfaceType type
        when returnType.startsWith((ExceptionCatcherResult).name)) {
      returnType = (ExceptionCatcherResult).name;
      final exceptionElement = type.typeArguments.single;
      exceptionType = exceptionElement.getDisplayString();
      if (exceptionElement.element?.librarySource?.uri case final Uri uri) {
        importPaths.add(uri.toString());
      }
    }
  }

  if (!returnTypes.contains(returnType)) {
    return null;
  }

  final params = object.parameters.map(ServerParam.fromElement).toList();

  return ServerLifecycleComponentMethod(
    name: name,
    isFuture: isFuture,
    returnType: returnType,
    parameters: params,
    exceptionType: exceptionType,
    import: ServerImports(importPaths),
  );
}