Skip to content

Instantly share code, notes, and snippets.

@naimurhasan
Last active July 4, 2021 20:53
Show Gist options
  • Save naimurhasan/cb9858c35e38d02c255b43ab7b511749 to your computer and use it in GitHub Desktop.
Save naimurhasan/cb9858c35e38d02c255b43ab7b511749 to your computer and use it in GitHub Desktop.
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
const String ApiBaseURL = "https://api.ebook.com.bd/ebook/v1";
httpGetCacheRequest(uri) async {
var client = http.Client();
p("opening shred pref");
// open shared preferrance
SharedPreferences prefs = await SharedPreferences.getInstance();
p("opened shred pref");
// check if this url last crowled time less than 1 minute
int lastFetchedAt = prefs.getInt("${uri}_last_fetched_at") ?? null;
if (lastFetchedAt != null) {
int currentEpoch = DateTime.now().millisecondsSinceEpoch;
int acceptableDelay = lastFetchedAt + 1000 * 60; // 1 minute addition
if (acceptableDelay > currentEpoch) {
print('fetched less than one minute ago so returning cache');
final filePath = prefs.get(uri);
try {
// open file
File dataFile = await File(filePath);
// return json
final data = await dataFile.readAsString();
final jsonMap = json.decode(data);
p('returning offline data');
return jsonMap;
} catch (e) {}
} else {
print('fetched more than one minute ago so fetching server');
}
}
try {
p('sending uri response');
var uriResponse = await client.get(
Uri.parse(uri),
);
p('end uri response');
final unicodeResponse = utf8.decode(uriResponse.bodyBytes);
final jsonMap = json.decode(unicodeResponse);
p('json map done');
/* --- whern online / save data ********/
// get url key file name
final responseAlreadyCached = prefs.containsKey(uri);
// if file exist open file
if (responseAlreadyCached) {
p('file already exist');
final fileName = prefs.get(uri);
File dataFile = await File(fileName);
await dataFile.writeAsString(unicodeResponse);
p('finish written file already exist');
} else {
// file doesn't already exist
// generate uuid
p('file doesn\'t already exist');
String uuid = Uuid().v1();
print('uuid ' + uuid);
// add .json after uuid
final fileName = uuid + '.json';
final appCachePath = await getApplicationDocumentsDirectory();
final responseFolder = 'response_cache';
final filePath = join(appCachePath.path, responseFolder, fileName);
p('new file path $filePath');
// open this json file
File dataFile = await File(filePath);
p('opened file');
await dataFile.create(recursive: true);
// write shared preferrance key = url, filename = uuid
await dataFile.writeAsString(unicodeResponse);
p('end written file doesn\'t already exist');
await prefs.setString(uri, filePath);
p('written file name in shared pref $filePath');
}
// save last crowled time
int lastCrowledEpoch = DateTime.now().millisecondsSinceEpoch;
await prefs.setInt("${uri}_last_fetched_at", lastCrowledEpoch);
return jsonMap;
} catch (e) {
print(e);
p('got error checking offline pair');
/* --- when offline ********/
// check if url exist in shared key
final responseAlreadyCached = prefs.containsKey(uri);
if (responseAlreadyCached) {
p('exist offline');
// get the file name
// check if file file exist
final filePath = prefs.get(uri);
try {
// open file
File dataFile = await File(filePath);
// return json
final data = await dataFile.readAsString();
final jsonMap = json.decode(data);
p('returning offline data');
return jsonMap;
} catch (e) {}
}
} finally {
client.close();
}
}
final p = print;
// comment above line and uncomment below
// to stop api debug print
// p(dynamic arguments)=>{};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment