loadDatabaseCacheResource method
Implementation
Future<dynamic> loadDatabaseCacheResource({required String url, Function? errorFunction}) async {
dynamic resource;
try {
_log("Loading cache resource for url " + url + "...");
Cache cache = Cache();
await cache.setLocalDatabasePath();
Map<String,dynamic >fetchResponse = await cache.fetchRecords(
condition: Cache.cacheUrl + "='" + url + "'");
_log(fetchResponse);
if (fetchResponse["status"] == "success") {
List records = fetchResponse["records"];
if (records.isNotEmpty) {
_log("Found file in cache.");
dynamic cacheRecord = records.first;
_log(cacheRecord);
resource = cacheRecord[Cache.cacheContent];
} else {
_log("File not found in cache.");
String directoryPath = await Simplify.rootAppDirectoryPath + "/localwebcache/";
String localPath= directoryPath+randomAlphaNumeric(10);
File cacheFile = new File(localPath);
while (await cacheFile.exists()) {
localPath = directoryPath + randomAlphaNumeric(10);
cacheFile = new File(localPath);
}
_log("Downloading cache file at " + localPath);
await WebServiceHelper.downloadFile(url: url, downloadPath: localPath);
_log("Downloaded cache file.");
resource = await cacheFile.readAsBytes();
cache.setFieldValue(Cache.cacheUrl, url);
cache.setFieldValue(Cache.localPath, localPath);
cache.setFieldValue(Cache.cacheContent, resource);
if (url.split('/').last.contains(".")) {
cache.setFieldValue(
Cache.cacheMime,
MimeTypes
.fromFileExtension[url.split('/').last.split(".").last]);
}
cache.setFieldValue(Cache.cacheSize, await cacheFile.length());
Map<String,dynamic >insertResponse = await cache.insertRecord();
_log(insertResponse);
if (insertResponse["status"] != "success") {
_log(insertResponse["message"]);
}
}
} else {
_log(fetchResponse["message"]);
}
} catch (ex,stack) {
_log(Simplify.getExceptionMessage(ex,stack: stack));
if (errorFunction != null) {
errorFunction(Simplify.getExceptionMessage(ex,stack: stack));
}
}
return resource;
}