preInject function

InjectionRequest preInject (
  1. Function handler,
  2. Reflector reflector
)

Predetermines what needs to be injected for a handler to run.

Implementation

InjectionRequest preInject(Function handler, Reflector reflector) {
  var injection = InjectionRequest();

  var closureMirror = reflector.reflectFunction(handler);

  if (closureMirror.parameters.isEmpty) return injection;

  // Load parameters
  for (var parameter in closureMirror.parameters) {
    var name = parameter.name;
    var type = parameter.type.reflectedType;

    var _Parameter = reflector.reflectType(Parameter);

    var p = parameter.annotations
        .firstWhere((m) => m.type.isAssignableTo(_Parameter),
            orElse: () => null)
        ?.reflectee as Parameter;
    //print(p);
    if (p != null) {
      injection.parameters[name] = Parameter(
        cookie: p.cookie,
        header: p.header,
        query: p.query,
        session: p.session,
        match: p.match,
        defaultValue: p.defaultValue,
        required: parameter.isNamed ? false : p.required != false,
      );
    }

    if (!parameter.isNamed) {
      if (!parameter.isRequired) injection.optional.add(name);

      if (type == RequestContext || type == ResponseContext) {
        injection.required.add(type);
      } else if (name == 'req') {
        injection.required.add(RequestContext);
      } else if (name == 'res') {
        injection.required.add(ResponseContext);
      } else if (type == dynamic) {
        injection.required.add(name);
      } else {
        injection.required.add([name, type]);
      }
    } else {
      injection.named[name] = type;
    }
  }
  return injection;
}