validimagereference_directive.js 2.3 KB
Newer Older
H
higashi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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.

/** The name of this directive. */
export const validImageReferenceValidationKey = 'validImageReference';

18
const invalidImageErrorMessage = 'invalidImageErrorMessage';
19

H
higashi 已提交
20 21 22 23 24 25 26 27 28 29 30 31
/**
 * Validates image reference
 *
 * @param {!angular.$resource} $resource
 * @param {!angular.$q} $q
 * @return {!angular.Directive}
 * @ngInject
 */
export default function validImageReferenceDirective($resource, $q) {
  return {
    restrict: 'A',
    require: 'ngModel',
32
    scope: {
33
      [invalidImageErrorMessage]: '=',
34
    },
H
higashi 已提交
35 36 37 38 39
    link: function(scope, element, attrs, ctrl) {
      /** @type {!angular.NgModelController} */
      let ngModelController = ctrl;

      ngModelController.$asyncValidators[validImageReferenceValidationKey] =
40
          (reference) => { return validate(reference, scope, $resource, $q); };
H
higashi 已提交
41 42 43 44 45 46 47 48 49
    },
  };
}

/**
 * @param {string} reference
 * @param {!angular.$resource} resource
 * @param {!angular.$q} q
 */
50
function validate(reference, scope, resource, q) {
H
higashi 已提交
51 52 53
  let deferred = q.defer();

  /** @type {!angular.Resource<!backendApi.ImageReferenceValiditySpec>} */
54
  let resourceClass = resource('api/v1/appdeployment/validate/imagereference');
H
higashi 已提交
55 56
  /** @type {!backendApi.ImageReferenceValiditySpec} */
  let spec = {reference: reference};
57

H
higashi 已提交
58 59 60 61 62 63 64
  resourceClass.save(
      spec,
      /**
       * @param {!backendApi.ImageReferenceValidity} validity
       */
      (validity) => {
        if (validity.valid === true) {
65
          scope[invalidImageErrorMessage] = '';
H
higashi 已提交
66 67
          deferred.resolve();
        } else {
68 69
          scope[invalidImageErrorMessage] = validity.reason;
          deferred.reject(scope[invalidImageErrorMessage]);
H
higashi 已提交
70 71
        }
      },
72
      (err) => {
73
        scope[invalidImageErrorMessage] = err.data;
74 75
        deferred.reject();
      });
H
higashi 已提交
76 77 78

  return deferred.promise;
}