Skip to content

Instantly share code, notes, and snippets.

@locskot
Created March 7, 2022 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save locskot/4e90859a7066a4649f5612734092fe93 to your computer and use it in GitHub Desktop.
Save locskot/4e90859a7066a4649f5612734092fe93 to your computer and use it in GitHub Desktop.
import '../../api/graphql_api.dart';
import '../../model/request_result_model.dart';
import '../../utils/log_service.dart';
import 'notification.dart';
abstract class NotificationsRepository {
NotificationsRepository();
factory NotificationsRepository.create(GraphqlAPI graphqlAPI) {
return NotificationRepositoryImpl(graphqlAPI);
}
Future<RequestResultModel> loadNotifications();
Future<RequestResultModel> loadNotification(String id);
Future<RequestResultModel> markAsRead(List<String> data);
}
class NotificationRepositoryImpl extends NotificationsRepository {
GraphqlAPI graphqlAPI;
NotificationRepositoryImpl(this.graphqlAPI);
@override
Future<RequestResultModel> loadNotifications() async {
final query = 'query { notifications { id title body type date unread enable data } }';
try {
final response = await graphqlAPI.sendAsync(query);
final notifications = <NotificationsItem>[];
response.data['data']['notifications']
?.forEach((n) => notifications.add(NotificationsItem.fromJson(n)));
return RequestResultModel(result: true, value: notifications);
} on Exception catch (e) {
LogService.log('Exception during loading notifications', exception: e);
return RequestResultModel(result: false, value: e);
}
}
Future<RequestResultModel> loadNotification(String id) async {
final query =
'query { notification(notificationId: "$id") { id title body type date unread enable data } }';
try {
final response = await graphqlAPI.sendAsync(query);
final notification = response.data['data']['notification'];
return RequestResultModel(
result: true, value: NotificationsItem.fromJson(notification));
} on Exception catch (e) {
LogService.log('Exception during loading notifications', exception: e);
return RequestResultModel(result: false, value: e);
}
}
@override
Future<RequestResultModel> markAsRead(List<String> data) async {
if (data?.isEmpty != false) {
return RequestResultModel(result: true);
}
var mutation = 'mutation { ';
for (var i = 0; i < data.length; i++) {
mutation += 'm$i: notificationMarkAsRead(notificationId: "${data[i]}") ';
}
mutation += '}';
try {
final response = await graphqlAPI.sendAsync(mutation);
var success = true;
response.data['data'].forEach((_, val) => success &= val == 'OK');
return RequestResultModel(result: success, value: data);
} on Exception catch (e) {
LogService.log('Exception during marking notifications as read',
exception: e);
return RequestResultModel(result: false, value: e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment