fetchNavs function
Method to fetch NAV data from the URL
Given a URL, this function fetches the data from the given URL.
It resolves with the fetched data if there is no error.
Otherwise, it rejects with an error message.
@param {String} url - URL to fetch data from
@returns {Future<String>}
The NAV data is updated every business day at 11:00 PM IST.
Implementation
Future<String> fetchNavs(String url) async {
final cacheDir = await getTemporaryDirectory();
final cacheFile = File('${cacheDir.path}/nav_data.txt');
final cacheExpiryFile = File('${cacheDir.path}/nav_data_expiry.txt');
// Check if cache exists and is not expired
if (await cacheFile.exists() && await cacheExpiryFile.exists()) {
final expiryDateStr = await cacheExpiryFile.readAsString();
final expiryDate = DateTime.parse(expiryDateStr);
final indianTime =
DateTime.now().toUtc().add(Duration(hours: 5, minutes: 30));
// if the time is before 11:00 PM IST and the cache is not expired
if (indianTime.isBefore(expiryDate) && indianTime.hour < 23) {
// Load from cache
return await cacheFile.readAsString();
} else {
logger.i('Cache expired or invalid time, fetching from URL');
}
} else {
logger.e('Cache files do not exist, fetching from URL');
}
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
// load the data from URL.
final result = response.body;
if (isError(result)) {
throw "Error in fetching NAVs."; // Check for errors
} else {
// Save data to cache
await cacheFile.writeAsString(result);
// Set cache expiry to 11:00 PM IST
final now = DateTime.now().toUtc().add(Duration(hours: 5, minutes: 30));
final expiryDate = DateTime(now.year, now.month, now.day, 23, 0, 0);
await cacheExpiryFile.writeAsString(expiryDate.toIso8601String());
return result; // Resolve the fetched text
}
} else {
throw "Error fetching data."; // Reject in case of an error
}
}