import { NotificationService } from "../service/NotificationService"; import { Sprintf } from "../singleton/Sprintf"; export function fetchHandler(response: Response, ns: NotificationService) { if (response.ok) { return response.json().then((json: any) => { // the status was ok and there is a json body // return Promise.resolve({ json: json, response: response }); ns.success('Message sent succesfully' + Sprintf(" (http code %d)", response.status)); }).catch((err: any) => { // the status was ok but there is no json body // return Promise.resolve({ response: response }); ns.success('Message sent succesfully' + Sprintf(" (http code %d)", response.status)); }); } else { return response.json().catch((err: any) => { // the status was not ok and there is no json body // throw new Error(response.statusText); ns.error('Some error occured. Please try again.'); }).then((json: any) => { // the status was not ok but there is a json body // throw new Error(json.error.message); // example error message returned by a REST // let delay = alertify.get('notifier', 'delay'); // alertify.set('notifier', 'delay', 30); let errorMessage = ""; json.errors.forEach(function(data: any) { errorMessage += Sprintf("Field Name: %s \n Rejected value: %s \n Reason: %s \n", data.field_name, data.rejected_value, data.error_message); }); ns.errorWithDelay(Sprintf('There were errors in your message - %s', errorMessage), 30); // alertify.set('notifier', 'delay', delay); }); } }