makeApiService static method

Future<void> makeApiService(
  1. String className,
  2. String value, {
  3. String folderPath = networkingFolder,
  4. bool forceCreate = false,
  5. bool addToConfig = true,
})

Creates a new API service.

Implementation

static Future<void> makeApiService(
  String className,
  String value, {
  String folderPath = networkingFolder,
  bool forceCreate = false,
  bool addToConfig = true,
}) async {
  String name = className.replaceAll(RegExp(r'(_?api_service)'), "");

  String filePath = '$folderPath/${name.snakeCase}_api_service.dart';

  await _makeDirectory(folderPath);
  await _checkIfFileExists(filePath, shouldForceCreate: forceCreate);
  await _createNewFile(
    filePath,
    value,
    onSuccess: () {
      final linkText = '${name.snakeCase}_api_service';
      final link = MetroConsole.hyperlink(linkText, filePath);
      MetroConsole.writeInGreen('[API Service] $link created 🎉');
    },
  );

  if (addToConfig == false) return;

  String classImport = makeImportPathApiService(name.snakeCase);
  await MetroService.addToConfig(
    configName: "decoders",
    classImport: classImport,
    createTemplate: (file) {
      String apiServiceName = "${name.pascalCase}ApiService";

      if (file.contains("final Map<Type, dynamic> apiDecoders =")) {
        RegExp reg = RegExp(
          r'final Map<Type, dynamic> apiDecoders = \{([^}]*)\};',
        );
        final match = _getFirstRegexMatch(reg, file);
        if (match == null) return file;
        String temp =
            """
final Map<Type, dynamic> apiDecoders = {$match
$apiServiceName: $apiServiceName(),
};""";

        return file.replaceFirst(reg, temp);
      }

      if (file.contains("final Map<Type, BaseApiService> apiDecoders =")) {
        RegExp reg = RegExp(
          r'final Map<Type, BaseApiService> apiDecoders = \{([^}]*)\};',
        );
        final match = _getFirstRegexMatch(reg, file);
        if (match == null) return file;
        String temp =
            """
final Map<Type, BaseApiService> apiDecoders = {$match
$apiServiceName: $apiServiceName(),
};""";

        return file.replaceFirst(reg, temp);
      }

      if (file.contains("final Map<Type, NyApiService> apiDecoders =")) {
        RegExp reg = RegExp(
          r'final Map<Type, NyApiService> apiDecoders = \{([^}]*)\};',
        );
        final match = _getFirstRegexMatch(reg, file);
        if (match == null) return file;
        String temp =
            """
final Map<Type, NyApiService> apiDecoders = {$match
$apiServiceName: $apiServiceName(),
};""";

        return file.replaceFirst(reg, temp);
      }

      return file;
    },
  );
}