makeModel static method

Future<void> makeModel(
  1. String className,
  2. String value, {
  3. String folderPath = modelsFolder,
  4. bool forceCreate = false,
  5. bool addToConfig = true,
  6. bool? skipIfExist = false,
  7. String? creationPath,
})

Creates a new Model.

Implementation

static Future<void> makeModel(
  String className,
  String value, {
  String folderPath = modelsFolder,
  bool forceCreate = false,
  bool addToConfig = true,
  bool? skipIfExist = false,
  String? creationPath,
}) async {
  String name = className.replaceAll(RegExp(r'(_?model)'), "");
  ReCase nameReCase = ReCase(name);

  // create missing directories in the project
  await _makeDirectory(folderPath);
  await createDirectoriesFromCreationPath(creationPath, folderPath);

  // create file path
  String filePath = createPathForDartFile(
    folderPath: folderPath,
    className: name,
    creationPath: creationPath,
  );

  if (skipIfExist == true) {
    if (await hasFile(filePath)) return;
  }
  await _checkIfFileExists(filePath, shouldForceCreate: forceCreate);
  await _createNewFile(
    filePath,
    value,
    onSuccess: () {
      final linkText = nameReCase.snakeCase;
      final link = MetroConsole.hyperlink(linkText, filePath);
      MetroConsole.writeInGreen('[Model] $link created 🎉');
    },
  );

  if (addToConfig == false) return;

  String classImport = makeImportPathModel(
    nameReCase.snakeCase,
    creationPath: creationPath ?? "",
  );

  await MetroService.addToConfig(
    configName: "decoders",
    classImport: classImport,
    createTemplate: (file) {
      String modelName = nameReCase.pascalCase;

      RegExp reg = RegExp(
        r'final Map<Type, dynamic> modelDecoders = \{([^}]*)\};',
      );
      final match = _getFirstRegexMatch(reg, file);
      if (match == null) {
        return file;
      }
      String template =
          """
final Map<Type, dynamic> modelDecoders = {$match
List<$modelName>: (data) => List.from(data).map((json) => $modelName.fromJson(json)).toList(),

$modelName: (data) => $modelName.fromJson(data),
};""";

      return file.replaceFirst(reg, template);
    },
  );
}