validprotocol.validator.ts 2.3 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.

S
Shu Muto 已提交
15 16 17 18 19 20 21 22 23 24
import { HttpClient } from '@angular/common/http';
import { Directive, forwardRef, Input } from '@angular/core';
import {
  AbstractControl,
  AsyncValidator,
  AsyncValidatorFn,
  NG_ASYNC_VALIDATORS,
} from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { debounceTime, map } from 'rxjs/operators';
H
haijiao.yin 已提交
25 26 27 28 29 30 31 32 33 34

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 已提交
35 36 37 38 39 40
    {
      provide: NG_ASYNC_VALIDATORS,
      useExisting: forwardRef(() => ProtocolValidator),
      multi: true,
    },
  ],
H
haijiao.yin 已提交
41 42 43 44 45 46
})
export class ProtocolValidator implements AsyncValidator {
  @Input() isExternal: boolean;

  constructor(private readonly http: HttpClient) {}

S
Shu Muto 已提交
47 48 49 50 51 52
  validate(
    control: AbstractControl
  ): Observable<{ [key: string]: boolean } | null> {
    return validateProtocol(this.http, this.isExternal)(control) as Observable<{
      [key: string]: boolean;
    } | null>;
H
haijiao.yin 已提交
53 54 55
  }
}

S
Shu Muto 已提交
56 57 58 59 60 61 62
export function validateProtocol(
  http: HttpClient,
  isExternal: boolean
): AsyncValidatorFn {
  return (
    control: AbstractControl
  ): Observable<{ [key: string]: boolean } | null> => {
H
haijiao.yin 已提交
63 64 65 66 67
    if (!control.value) {
      return Observable.of(null);
    } else {
      const protocol = control.value;
      return http
S
Shu Muto 已提交
68 69 70 71 72 73 74 75 76 77 78
        .post<{ valid: boolean }>('api/v1/appdeployment/validate/protocol', {
          protocol,
          isExternal,
        })
        .first()
        .pipe(
          debounceTime(500),
          map(res => {
            return !res.valid ? { [validProtocolValidationKey]: true } : null;
          })
        );
H
haijiao.yin 已提交
79 80 81
    }
  };
}