-
Notifications
You must be signed in to change notification settings - Fork 21
/
check-item-existing.directive.ts
82 lines (74 loc) · 2.52 KB
/
check-item-existing.directive.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { Directive, Input } from '@angular/core';
import { AbstractControl, AsyncValidator, NG_ASYNC_VALIDATORS, ValidatorFn, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/first';
import 'rxjs/add/operator/map'
import { HttpClient } from '@angular/common/http';
import { AppInitService } from '../../app.init.service';
import { MessageService } from '../message-service/message.service';
@Directive({
selector: '[checkItemExisting]',
providers: [
{provide: NG_ASYNC_VALIDATORS, useExisting: CheckItemExistingDirective, multi: true}
]
})
export class CheckItemExistingDirective implements AsyncValidator {
@Input() checkItemExisting;
@Input() userID: number = 0;
valFn: ValidatorFn = Validators.nullValidator;
constructor(private http: HttpClient,
private appInitService: AppInitService,
private messageService: MessageService) {
}
checkUserExists(target: string, value: string, userID: number): Observable<{[key: string]: any}> {
return this.http.get("/api/v1/user-exists", {
observe: "response",
params: {
'target': target,
'value': value,
'user_id': userID.toString()
}
})
.map(()=>this.valFn)
.catch(err=>{
this.messageService.cleanNotification();
if(err && err.status === 409) {
return Observable.of({ 'checkItemExisting': { value } });
}
});
}
checkProjectExists(token: string, projectName: string): Observable<{[key: string]: any}>{
return this.http.head('/api/v1/projects', {
observe: "response",
params: {
'project_name': projectName
}
})
.map(()=>this.valFn)
.catch(err=>{
this.messageService.cleanNotification();
if(err && err.status === 409) {
return Observable.of({ 'checkItemExisting': { projectName } });
}
});
}
validate(control: AbstractControl): Observable<{[key: string]: any}> {
return control.valueChanges
.debounceTime(200)
.distinctUntilChanged()
.switchMap(value=> {
switch(this.checkItemExisting) {
case 'username':
case 'email':
return this.checkUserExists(this.checkItemExisting, value, this.userID);
case 'project':
return this.checkProjectExists(this.appInitService.token, value);
}
})
.first();
}
}