makeModel static method

dynamic 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 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: className,
      creationPath: creationPath);

  if (skipIfExist == true) {
    if (await hasFile(filePath)) return;
  }
  await _checkIfFileExists(filePath, shouldForceCreate: forceCreate);
  await _createNewFile(filePath, value, onSuccess: () {
    MetroConsole.writeInGreen('[Model] ${nameReCase.snakeCase} 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;
        if (file.contains(modelName)) {
          return "";
        }

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

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

        return file.replaceFirst(
            RegExp(r'final Map<Type, dynamic> modelDecoders = \{([^}]*)\};'),
            template);
      });
}