ServerLifecycleComponent.fromClassElement constructor

ServerLifecycleComponent.fromClassElement(
  1. ClassElement element,
  2. AnnotationArguments arguments
)

Implementation

factory ServerLifecycleComponent.fromClassElement(
  ClassElement element,
  AnnotationArguments arguments,
) {
  final methods = element.methods
      .map(ServerLifecycleComponentMethod.fromElement)
      .whereType<ServerLifecycleComponentMethod>()
      .toList();

  final guards = <ServerLifecycleComponentMethod>[];
  final middlewares = <ServerLifecycleComponentMethod>[];
  final interceptors = (
    pre: <ServerLifecycleComponentMethod>[],
    post: <ServerLifecycleComponentMethod>[],
  );
  final exceptionCatchers = <ServerLifecycleComponentMethod>[];

  for (final method in methods) {
    final _ = switch (true) {
      _ when method.isGuard => guards.add(method),
      _ when method.isMiddleware => middlewares.add(method),
      _ when method.isInterceptorPre => interceptors.pre.add(method),
      _ when method.isInterceptorPost => interceptors.post.add(method),
      _ when method.isExceptionCatcher => exceptionCatchers.add(method),
      _ => null,
    };
  }

  final constructor = element.constructors.firstWhereOrNull(
    (e) => e.isPublic,
  );

  if (constructor == null) {
    throw ArgumentError.value(
      LifecycleComponent,
      'type',
      'Expected a class element with a public constructor',
    );
  }

  final params = constructor.formalParameters.map((e) {
    final param = ServerParam.fromElement(e);

    if (arguments.all[param.name] case final arg?) {
      param.argument = arg;
    }

    return param;
  }).toList();

  final name = element.name3;

  if (name == null) {
    throw Exception('Class name is null');
  }

  return ServerLifecycleComponent(
    name: name,
    guards: guards,
    middlewares: middlewares,
    interceptors: interceptors,
    exceptionCatchers: exceptionCatchers,
    params: params,
    import: ServerImports.fromElement(constructor.returnType.element),
    arguments: arguments,
    genericTypes: element.typeParameters
        .map(ServerGenericType.fromElement)
        .toList(),
  );
}