1 import { Directive, forwardRef } from '@angular/core';
2 import { NG_VALIDATORS, NG_ASYNC_VALIDATORS, AbstractControl, ValidationErrors, 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, of} from 'rxjs';
6 import {single, switchMap, catchError} from 'rxjs/operators';
7 import {Injectable} from '@angular/core';
9 @Injectable({providedIn: 'root'})
10 export class PatronBarcodeValidator implements AsyncValidator {
12 private auth: AuthService,
13 private net: NetService) {
16 validate = (control: FormControl) => {
17 return this.parseActorCall(this.net.request(
19 'open-ils.actor.get_barcodes',
21 this.auth.user().ws_ou(),
22 'actor', control.value.trim()));
25 private parseActorCall = (actorCall: Observable<any>) => {
28 switchMap(() => of(null)),
30 if (err instanceof EmptyError) {
31 return of({ patronBarcode: 'No patron found with that barcode' });
32 } else if ('Sequence contains more than one element' === err) {
33 return of({ patronBarcode: 'Barcode matches more than one patron' });
40 selector: '[egValidPatronBarcode]',
42 provide: NG_ASYNC_VALIDATORS,
43 useExisting: forwardRef(() => PatronBarcodeValidator),
47 export class PatronBarcodeValidatorDirective {
49 private pbv: PatronBarcodeValidator
52 validate = (control: FormControl) => {
53 this.pbv.validate(control);