createArgFromQuery function

Expression createArgFromQuery(
  1. ServerQueryAnnotation annotation,
  2. ServerParam param
)

Implementation

Expression createArgFromQuery(
  ServerQueryAnnotation annotation,
  ServerParam param,
) {
  var queryVar = refer('context').property('request');

  if (annotation.all) {
    queryVar = queryVar.property('queryParametersAll');
  } else {
    queryVar = queryVar.property('queryParameters');
  }

  var queryValue = queryVar.index(literalString(annotation.name ?? param.name));

  if (annotation.all) {
    queryValue = switch (param.type) {
      final type when type.startsWith('Iterable') => queryValue,
      final type when type.startsWith('Set') =>
        queryValue.nullSafeProperty('toSet').call([]),
      _ => queryValue = queryValue.nullSafeProperty('toList').call([])
    };
  }

  final acceptsNull = annotation.acceptsNull;
  if ((acceptsNull != null && !acceptsNull) ||
      (!param.isNullable && annotation.pipe == null)) {
    queryValue = queryValue.ifNullThen(
      createMissingArgumentException(
        key: annotation.name ?? param.name,
        location: '@${AnnotationType.query.name}',
      ).thrown.parenthesized,
    );
  }

  if (annotation.pipe case final pipe?) {
    final name = annotation.name;
    return createPipe(
      pipe,
      annotationArgument: name == null ? literalNull : literalString(name),
      nameOfParameter: param.name,
      type: annotation.all ? AnnotationType.queryAll : AnnotationType.query,
      access: queryValue,
    );
  }

  return queryValue;
}