clearExpiredCache function

Future<void> clearExpiredCache(
  1. bool showLog,
  2. int ttl, [
  3. String? folder
])

Clears expired cache files in the specified folder.

Implementation

Future<void> clearExpiredCache(bool showLog, int ttl, [String? folder]) async {
  Directory baseDir = await getTemporaryDirectory();
  final cacheDir = Directory('${baseDir.path}/DioCache/$folder');

  if (!cacheDir.existsSync()) {
    if (showLog) {
      Logger.log('πŸ“‚ Cache directory does not exist: ${cacheDir.path}');
    }
    return;
  }

  DateTime now = DateTime.now();

  for (FileSystemEntity entity in cacheDir.listSync()) {
    if (entity is File) {
      DateTime lastModified = entity.lastModifiedSync();
      DateTime expiryTime = lastModified.add(Duration(seconds: ttl));

      if (expiryTime.isBefore(now)) {
        try {
          entity.deleteSync();
          if (showLog) Logger.log('πŸ—‘οΈ Deleted expired cache: ${entity.path}');
        } catch (e) {
          if (showLog) Logger.error('❌ Error deleting file: ${entity.path}', e);
        }
      }
    }
  }

  if (showLog) {
    Logger.log('βœ… Cache cleanup completed for folder: ${cacheDir.path}');
  }
}