bitwarden-estensione-browser/libs/angular/src/directives/api-action.directive.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

50 lines
1.5 KiB
TypeScript
Raw Normal View History

import { Directive, ElementRef, Input, OnChanges } from "@angular/core";
2022-06-14 17:10:53 +02:00
import { LogService } from "@bitwarden/common/abstractions/log.service";
import { ErrorResponse } from "@bitwarden/common/models/response/errorResponse";
import { ValidationService } from "../services/validation.service";
/**
* 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.
*/
@Directive({
selector: "[appApiAction]",
})
export class ApiActionDirective implements OnChanges {
@Input() appApiAction: Promise<any>;
constructor(
private el: ElementRef,
private validationService: ValidationService,
private logService: LogService
) {}
ngOnChanges(changes: any) {
if (this.appApiAction == null || this.appApiAction.then == null) {
return;
}
2021-12-16 13:36:21 +01:00
this.el.nativeElement.loading = true;
2021-12-16 13:36:21 +01:00
this.appApiAction.then(
(response: any) => {
this.el.nativeElement.loading = false;
2021-12-16 13:36:21 +01:00
},
(e: any) => {
this.el.nativeElement.loading = false;
2021-12-16 13:36:21 +01:00
if ((e as ErrorResponse).captchaRequired) {
this.logService.error("Captcha required error response: " + e.getSingleMessage());
2021-12-16 13:36:21 +01:00
return;
}
this.logService?.error(`Received API exception: ${e}`);
this.validationService.showError(e);
2021-12-16 13:36:21 +01:00
}
);
}
}