fetchNotifications method

dynamic fetchNotifications()

Implementation

fetchNotifications() async {
  final configData = state["config"];
  final notifData = state["notifData"];
  final isFirstCall = notifData["lastFetchedOn"] == null;
  final currentTimeStamp = epochNow();
  final prevMonthTimeStamp =
      currentTimeStamp - configData["batchTimeInterval"];
  final currentFetchFrom = notifData["lastFetchedOn"] ?? prevMonthTimeStamp;
  bool? hasNewData;
  try {
    final response = await ApiClient()
        .getNotifications(state["config"], currentFetchFrom, null);
    if (response.statusCode == 200) {
      final respData = convert.jsonDecode(response.body);
      print("UNREAD NOTIFICATIONS ${respData["unread"]}");
      hasNewData = isFirstCall == false && respData["results"].length > 0;
      final newNotifications = isFirstCall
          ? [...respData["results"]]
          : [...respData["results"], ...notifData["notifications"]];
      updateNotifData({
        "notifications": newNotifications,
        "unSeenCount": notifData["unSeenCount"] + respData["unread"],
        "lastFetchedOn": currentTimeStamp,
        "firstFetchedOn":
            isFirstCall ? prevMonthTimeStamp : notifData["firstFetchedOn"]
      }, updateRerender: hasNewData || isFirstCall);

      // for emitting new notification event
      if (hasNewData) {
        latestNotifications = [...respData["results"]];
      }

      // store in local storage
      final storageData = {
        "notifications": [...newNotifications.take(configData["batchSize"])],
        "subscriberId": configData["subscriberId"]
      };
      setClientNotificationStorage(configData["storage_key"], storageData);
    } else {
      print(
          'SUPRSEND: api error getting latest notifications ${response.statusCode}');
    }
  } catch (e) {
    print('SUPRSEND: error getting latest notifications ${e.toString()}');
  }
  var duration = Duration(seconds: configData["pollingInterval"]);
  var timerId = Timer(duration, () => {fetchNotifications()});
  updateNotifData({"pollingTimerId": timerId});
}