validprotocol.validator.ts 2.2 KB
Newer Older
H
haijiao.yin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2017 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16
import {HttpClient} from '@angular/common/http';
import {Directive, forwardRef, Input} from '@angular/core';
M
Marcin Maciaszczyk 已提交
17
import {AbstractControl, AsyncValidator, AsyncValidatorFn, NG_ASYNC_VALIDATORS} from '@angular/forms';
18 19
import {Observable, of} from 'rxjs';
import {debounceTime, first, map} from 'rxjs/operators';
H
haijiao.yin 已提交
20 21 22 23 24 25 26 27 28 29

export const validProtocolValidationKey = 'validProtocol';

/**
 * A validator directive which checks the underlining ngModel's given name is unique or not.
 * If the name exists, error with name `uniqueName` will be added to errors.
 */
@Directive({
  selector: '[kdValidProtocol]',
  providers: [
S
Shu Muto 已提交
30 31 32 33 34 35
    {
      provide: NG_ASYNC_VALIDATORS,
      useExisting: forwardRef(() => ProtocolValidator),
      multi: true,
    },
  ],
H
haijiao.yin 已提交
36 37 38 39 40 41
})
export class ProtocolValidator implements AsyncValidator {
  @Input() isExternal: boolean;

  constructor(private readonly http: HttpClient) {}

S
Shu Muto 已提交
42 43 44 45
  validate(control: AbstractControl): Observable<{[key: string]: boolean} | null> {
    return validateProtocol(this.http, this.isExternal)(control) as Observable<{
      [key: string]: boolean;
    } | null>;
H
haijiao.yin 已提交
46 47 48
  }
}

49
export function validateProtocol(http: HttpClient, isExternal: boolean): AsyncValidatorFn {
S
Shu Muto 已提交
50
  return (control: AbstractControl): Observable<{[key: string]: boolean} | null> => {
H
haijiao.yin 已提交
51
    if (!control.value) {
52
      return of(null);
H
haijiao.yin 已提交
53
    }
M
Marcin Maciaszczyk 已提交
54 55 56 57 58 59
    const protocol = control.value;
    return http
      .post<{valid: boolean}>('api/v1/appdeployment/validate/protocol', {
        protocol,
        isExternal,
      })
60
      .pipe(first())
M
Marcin Maciaszczyk 已提交
61 62 63 64
      .pipe(
        debounceTime(500),
        map(res => {
          return !res.valid ? {[validProtocolValidationKey]: true} : null;
65
        })
M
Marcin Maciaszczyk 已提交
66
      );
H
haijiao.yin 已提交
67 68
  };
}