replaceKeys function
Implementation
Map<String, dynamic> replaceKeys(Map<String, dynamic> data,
List<Map<String, dynamic>> mapping, List<String> requiredMapping) {
Map<String, dynamic> replacedData = {};
Map<String, String> errors = {};
// Check if all required columns are available in data
for (String requiredColumn in requiredMapping) {
if (!data.containsKey(requiredColumn)) {
errors[requiredColumn] =
'$requiredColumn is required but not found in data';
}
}
// If there are missing required columns, return an error
if (errors.isNotEmpty) {
return {'message': 'Required keys are missing', 'errors': errors};
}
// Process data and perform key replacement
for (String key in data.keys) {
final mappingEntry = mapping.firstWhere(
(entry) => entry['client_column_name'] == key,
orElse: () => {},
);
if (mappingEntry.isNotEmpty) {
final mappingKey = mappingEntry['column_name'];
final expectedType = mappingEntry['type'];
final value = data[key];
if (expectedType == 'time' ||
expectedType == 'number' ||
value.runtimeType.toString() == capitalize(expectedType)) {
replacedData[mappingKey] = value;
} else {
errors[key] = 'Type mismatch for $key. Expected type: $expectedType';
}
}
}
// If there are type mismatch errors, return an error
if (errors.isNotEmpty) {
return {'message': 'Type mismatch', 'errors': errors};
} else {
return replacedData;
}
}