LP1816475: Booking module refresh
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / booking / booking_resource_validator.directive.ts
1 import {Directive, forwardRef, Injectable} from '@angular/core';
2 import {NG_ASYNC_VALIDATORS, AsyncValidator, FormControl} from '@angular/forms';
3 import {of} from 'rxjs';
4 import {switchMap, catchError} from 'rxjs/operators';
5 import {PcrudService} from '@eg/core/pcrud.service';
6 import {BookingModule} from './booking.module';
7
8 @Injectable({providedIn: BookingModule})
9 export class BookingResourceBarcodeValidator implements AsyncValidator {
10     constructor(
11         private pcrud: PcrudService) {
12     }
13
14     validate = (control: FormControl) => {
15         return this.pcrud.search('brsrc',
16             {'barcode' : control.value},
17             {'limit': 1}).pipe(
18                 switchMap(() => of(null)),
19                 catchError((err) => {
20                     return of({ resourceBarcode: 'No resource found with that barcode' });
21                 }));
22     }
23 }
24
25 @Directive({
26     selector: '[egValidBookingResourceBarcode]',
27     providers: [{
28         provide: NG_ASYNC_VALIDATORS,
29         useExisting: forwardRef(() => BookingResourceBarcodeValidator),
30         multi: true
31     }]
32 })
33 export class BookingResourceBarcodeValidatorDirective {
34     constructor(
35         private validator: BookingResourceBarcodeValidator
36     ) { }
37
38     validate = (control: FormControl) => {
39         this.validator.validate(control);
40     }
41 }
42