2018-04-04 14:22:55 +02:00
|
|
|
import { Directive, ElementRef, Input, OnChanges } from "@angular/core";
|
2021-07-22 19:28:45 +02:00
|
|
|
|
2022-02-22 15:39:11 +01:00
|
|
|
import { LogService } from "jslib-common/abstractions/log.service";
|
2021-09-17 14:57:31 +02:00
|
|
|
import { ErrorResponse } from "jslib-common/models/response/errorResponse";
|
2018-04-04 14:22:55 +02:00
|
|
|
|
|
|
|
import { ValidationService } from "../services/validation.service";
|
|
|
|
|
2022-04-12 03:48:33 +02:00
|
|
|
/**
|
|
|
|
* Provides error handling, in particular for any error returned by the server in an api call.
|
|
|
|
* Attach it to a <form> element and provide the name of the class property that will hold the api call promise.
|
|
|
|
* e.g. <form [appApiAction]="this.formPromise">
|
|
|
|
* Any errors/rejections that occur will be intercepted and displayed as error toasts.
|
|
|
|
*/
|
2018-04-04 14:22:55 +02:00
|
|
|
@Directive({
|
|
|
|
selector: "[appApiAction]",
|
|
|
|
})
|
|
|
|
export class ApiActionDirective implements OnChanges {
|
|
|
|
@Input() appApiAction: Promise<any>;
|
|
|
|
|
2021-07-22 19:28:45 +02:00
|
|
|
constructor(
|
|
|
|
private el: ElementRef,
|
|
|
|
private validationService: ValidationService,
|
|
|
|
private logService: LogService
|
|
|
|
) {}
|
2018-04-04 14:22:55 +02:00
|
|
|
|
|
|
|
ngOnChanges(changes: any) {
|
|
|
|
if (this.appApiAction == null || this.appApiAction.then == null) {
|
2021-07-22 19:28:45 +02:00
|
|
|
return;
|
2018-04-04 14:22:55 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
|
2018-04-04 14:22:55 +02:00
|
|
|
this.el.nativeElement.loading = true;
|
2021-12-16 13:36:21 +01:00
|
|
|
|
2018-04-04 14:22:55 +02:00
|
|
|
this.appApiAction.then(
|
|
|
|
(response: any) => {
|
|
|
|
this.el.nativeElement.loading = false;
|
2021-12-16 13:36:21 +01:00
|
|
|
},
|
2018-04-04 14:22:55 +02:00
|
|
|
(e: any) => {
|
|
|
|
this.el.nativeElement.loading = false;
|
2021-12-16 13:36:21 +01:00
|
|
|
|
2022-03-18 03:24:22 +01:00
|
|
|
if ((e as ErrorResponse).captchaRequired) {
|
2021-07-22 19:28:45 +02:00
|
|
|
this.logService.error("Captcha required error response: " + e.getSingleMessage());
|
2021-12-16 13:36:21 +01:00
|
|
|
return;
|
|
|
|
}
|
2021-08-31 21:59:54 +02:00
|
|
|
this.logService?.error(`Received API exception: ${e}`);
|
2018-04-04 14:22:55 +02:00
|
|
|
this.validationService.showError(e);
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
2018-04-04 14:22:55 +02:00
|
|
|
}
|