generateDataSourceMethod method

String generateDataSourceMethod(
  1. ApiGenerationConfig config, {
  2. String? headers,
})

Implementation

String generateDataSourceMethod(
  ApiGenerationConfig config, {
  String? headers,
}) {
  final paramPath = <String>[];
  parse(config.pathUrl ?? '', parameters: paramPath);

  final bodyClass =
      typeResolver.resolveBodyClass(config.apiClassName, config.bodyList);
  final bodyImpl = config.bodyList
      ? 'body: jsonEncode(body.map((e) => e.toMap()).toList()),'
      : 'body: body.toMap()${typeResolver.isMultipart(config.method) ? '.map((key, value) => MapEntry(key, value.toString()))' : ''},${typeResolver.isMultipart(config.method) ? ' files: body.files,' : ''}';

  final responseClass = typeResolver.whenMethod(
    config.method,
    onStream: () => typeResolver.resolveStreamResponseClass(config),
    onFuture: () => typeResolver.resolveResponseClass(config),
  );

  final responseImpl = typeResolver.whenMethod(
    config.method,
    onStream: () => typeResolver.generateStreamResponseReturn(config),
    onFuture: () => typeResolver.generateResponseReturn(config),
  );

  final apiMethod = typeResolver.isMultipart(config.method)
      ? config.method == 'multipart'
          ? 'postMultipart'
          : config.method
      : config.method;

  final apiEndpoint = paramPath.isEmpty
      ? '${config.projectName.pascalCase}Endpoints.${config.apiMethodName}${config.appsName?.pascalCase ?? ''}'
      : '${config.projectName.pascalCase}Endpoints.${config.apiMethodName}${config.appsName?.pascalCase ?? ''}(${paramPath.map((e) => 'body.${e.camelCase}').join(',')})';

  final apiCacheStrategy = typeResolver.isApplyCacheStrategy(config.method)
      ? config.cacheStrategy.toParamCacheStrategy(
          ttl: config.ttl, keepExpiredCache: config.keepExpiredCache)
      : '';

  final headersConfig = headers != null
      ? 'headers: $headers.map((key, value) => MapEntry(key, value.toString()))..addAll(headers ?? {}),'
          .replaceAll('\n', ' ')
      : null;

  return '''@override
${typeResolver.whenMethod(
    config.method,
    onStream: () {
      return '''${typeResolver.resolveFlutterClassOfMethod(config.method)}<$responseClass> ${config.apiMethodName}($bodyClass body,{Map<String, String>? headers,}) async* {
  final responses = http.$apiMethod($apiEndpoint, $bodyImpl${headersConfig ?? 'headers: headers,'});
  $responseImpl
}''';
    },
    onFuture: () {
      return '''${typeResolver.resolveFlutterClassOfMethod(config.method)}<$responseClass> ${config.apiMethodName}($bodyClass body,{Map<String, String>? headers, ${typeResolver.isApplyCacheStrategy(config.method) ? 'CacheStrategy? cacheStrategy,' : ''}}) async {
  final response = await http.$apiMethod($apiEndpoint, $bodyImpl${headersConfig ?? 'headers: headers,'}$apiCacheStrategy);
  $responseImpl
}''';
    },
  )}''';
}