sync static method
Synchronizes an existing Dart model file with a new JSON response.
Implementation
static void sync(String modelFilePath, dynamic newJson, String modelName, ModelRegistry registry) {
final ProgressIndicator progress = ProgressIndicator();
final file = File(modelFilePath);
if (!file.existsSync()) {
throw Exception('Model file not found: $modelFilePath');
}
progress.start('Analyzing existing model...');
final content = file.readAsStringSync();
final existingFields = _extractFields(content);
final baseObject = JsonParser.extractBaseObject(newJson);
final jsonFields = <String, String>{};
baseObject.forEach((key, value) {
jsonFields[StringUtils.snakeToCamel(key)] = TypeDetector.detectType(value, key, registry);
});
final newFields = <String, String>{};
jsonFields.forEach((name, type) {
if (!existingFields.containsKey(name)) {
newFields[name] = type;
}
});
progress.stop();
if (newFields.isEmpty) {
print('ā¹ No new fields detected in $modelName.');
return;
}
print('\nš Model Update Detected for $modelName');
print('New fields:');
newFields.forEach((name, type) => print(' * $name : $type'));
stdout.write('\nContinue updating $modelName? (y/n, default: y): ');
final input = stdin.readLineSync()?.toLowerCase();
if (input == 'n') {
print('ā Sync cancelled for $modelName.');
return;
}
progress.start('Updating models...');
// Use ModelBuilder to generate the updated model and any new nested models
final builder = ModelBuilder(modelName, baseObject, registry);
final allModels = builder.getAllModels();
final outputDir = p.dirname(modelFilePath);
for (var model in allModels) {
// If it's the model we're syncing, always write it.
if (model.modelName == modelName) {
final code = model.build();
DartWriter.write(modelFilePath, code);
registry.markProcessed(modelName);
continue;
}
if (registry.isProcessed(model.modelName)) continue;
final nestedFileName = StringUtils.camelToSnake(model.modelName);
final nestedPath = p.join(outputDir, '$nestedFileName.dart');
// If it doesn't exist, generate it.
if (!File(nestedPath).existsSync()) {
final code = model.build();
DartWriter.write(nestedPath, code);
registry.markProcessed(model.modelName);
}
}
progress.success('Successfully synced $modelName.');
}