github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/ui/app/components/policy-editor.js (about)

     1  import Component from '@glimmer/component';
     2  import { action } from '@ember/object';
     3  import { inject as service } from '@ember/service';
     4  import { alias } from '@ember/object/computed';
     5  import messageForError from 'nomad-ui/utils/message-from-adapter-error';
     6  
     7  export default class PolicyEditorComponent extends Component {
     8    @service flashMessages;
     9    @service router;
    10    @service store;
    11  
    12    @alias('args.policy') policy;
    13  
    14    @action updatePolicyRules(value) {
    15      this.policy.set('rules', value);
    16    }
    17  
    18    @action async save(e) {
    19      if (e instanceof Event) {
    20        e.preventDefault(); // code-mirror "command+enter" submits the form, but doesnt have a preventDefault()
    21      }
    22      try {
    23        const nameRegex = '^[a-zA-Z0-9-]{1,128}$';
    24        if (!this.policy.name?.match(nameRegex)) {
    25          throw new Error(
    26            'Policy name must be 1-128 characters long and can only contain letters, numbers, and dashes.'
    27          );
    28        }
    29  
    30        if (
    31          this.policy.isNew &&
    32          this.store.peekRecord('policy', this.policy.name)
    33        ) {
    34          throw new Error(
    35            `A policy with name ${this.policy.name} already exists.`
    36          );
    37        }
    38  
    39        this.policy.id = this.policy.name;
    40  
    41        await this.policy.save();
    42  
    43        this.flashMessages.add({
    44          title: 'Policy Saved',
    45          type: 'success',
    46          destroyOnClick: false,
    47          timeout: 5000,
    48        });
    49  
    50        this.router.transitionTo('policies');
    51      } catch (error) {
    52        console.log('error and its', error);
    53        this.flashMessages.add({
    54          title: `Error creating Policy ${this.policy.name}`,
    55          message: messageForError(error),
    56          type: 'error',
    57          destroyOnClick: false,
    58          sticky: true,
    59        });
    60      }
    61    }
    62  }