sendNotification method
Sends a notification to a device token
Implementation
Future<http.Response> sendNotification(
String serviceId,
FcmMessage message,
) async {
await _ensureValidAuth(serviceId);
if(!queues.containsKey(serviceId)){
throw Exception('Invalid serviceId');
}
return queues[serviceId]!.add<http.Response>(() async {
// Ensure we have a valid token before proceeding
final url = Uri.parse('https://fcm.googleapis.com/v1/projects/$_projectId/messages:send');
final notificationData = {
'message': message.toJson(),
};
// print(jsonEncode(notificationData) );
return _authClient[serviceId]!.post(
url,
headers: {
'Authorization': 'Bearer $_accessToken',
'Content-Type': 'application/json',
},
body: json.encode(notificationData),
).then((vla){
// ignore: avoid_print
print(vla.body);
return vla;
// ignore: invalid_return_type_for_catch_error
}).catchError(print);
})
.timeout(const Duration(seconds: 3))
.onError((e,s){
final client = http.Client();
if(serviceCallbackUrls.containsKey(serviceId)){
final url = Uri.tryParse(serviceCallbackUrls[serviceId]!['fail'].toString());
if (url != null) {
client.post(
url,
body: {'error': e.toString()},
headers: {
'Content-Type': 'application/json',
},
).timeout(const Duration(seconds: 3));
}
}
final res=DefaultResponse(
message: 'fail',
data: e.toString(),
statusCode:422,
);
return http.Response(
jsonEncode(res.toMap()),
res.statusCode,
);
}).then((onValue){
if (serviceCallbackUrls.containsKey(serviceId)) {
final client = http.Client();
final url = Uri.tryParse(serviceCallbackUrls[serviceId]!['success'].toString());
if (url != null) {
client.post(
url,
body: onValue.body,
headers: onValue.headers,
).timeout(const Duration(seconds: 3));
}
}
final res = DefaultResponse(
message: onValue.statusCode == 200 ? 'success' : 'info',
data: onValue.body,
statusCode: onValue.statusCode,
);
return http.Response(
jsonEncode(res.toMap()),
res.statusCode,
);
});
}