1 import { Directive, forwardRef, Injectable } from '@angular/core';
2 import { NG_ASYNC_VALIDATORS, AsyncValidator, FormControl } from '@angular/forms';
3 import {NetService} from '@eg/core/net.service';
4 import {AuthService} from '@eg/core/auth.service';
5 import {EmptyError, Observable, SequenceError, of} from 'rxjs';
6 import {single, switchMap, catchError} from 'rxjs/operators';
8 @Injectable({providedIn: 'root'})
9 export class PatronBarcodeValidator implements AsyncValidator {
11 private auth: AuthService,
12 private net: NetService) {
15 validate = (control: FormControl) => {
16 return this.parseActorCall(this.net.request(
18 'open-ils.actor.get_barcodes',
20 this.auth.user().ws_ou(),
21 'actor', control.value.trim()));
24 private parseActorCall = (actorCall: Observable<any>) => {
27 switchMap(() => of(null)),
28 catchError((err: unknown) => {
29 if (err instanceof EmptyError) {
30 return of({ patronBarcode: 'No patron found with that barcode' });
31 } else if (err instanceof SequenceError) {
32 return of({ patronBarcode: 'Barcode matches more than one patron' });
39 selector: '[egValidPatronBarcode]',
41 provide: NG_ASYNC_VALIDATORS,
42 useExisting: forwardRef(() => PatronBarcodeValidator),
46 export class PatronBarcodeValidatorDirective {
48 private pbv: PatronBarcodeValidator
51 validate = (control: FormControl) => {
52 this.pbv.validate(control);