add-horse.component.ts 3.14 KB
Newer Older
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
1 2 3 4 5 6 7 8 9 10 11 12 13
import { Component, OnInit } from '@angular/core';
import { Horse } from '../../dto/horse';
import { HorseService } from '../../service/horse.service';

@Component({
  selector: 'app-add-horse',
  templateUrl: './add-horse.component.html',
  styleUrls: ['./add-horse.component.scss']
})
export class AddHorseComponent implements OnInit {
  error = false;
  success: string;
  errorMessage = '';
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
14 15
  horse: Horse = new Horse(null, null, null, null, null, null, null, null);
  imageToUpload: File = null;
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
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

  constructor(private horseService: HorseService) { }

  ngOnInit(): void {}

  /**
   * Will be called on a click on the success alert close button
   */
  public vanishAlert() {
    this.success = null;
  }

  /**
   * Will be called on a click on the error alert close button
   */
  public vanishError() {
    this.errorMessage = null;
  }

  /**
   * Creates a new horse and loads it
   * @param horse
   */
  public addHorse() {
    console.log("POST horse to API")
    console.log(this.horse);
    // TODO: Make it possible for the horse to be added with an owner
    this.horseService.addHorse(this.horse).subscribe(
      (result: Horse) => {
        this.success = result.name;
      },
      error => {
        this.defaultServiceErrorHandling(error);
      }
    );
  }

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
  /**
   * Handles the input on the image input.
   * Inspired from:
   * https://stackoverflow.com/questions/47936183/angular-file-upload
   * @param files
   */
  public handleImageInput(files: FileList) {
    var imageFile: File = files.item(0);

    // Generate a random bytes name to avoid conflicts
    var fileExt: string = imageFile.name.split('.').pop();
    var newFileName: string = this.generateHex(20) + '.' + fileExt;
    this.horse.imagePath = newFileName;

    // Upload the file
    this.uploadFile(imageFile, newFileName)
  }

  /**
   * Uploads the file to the backend with the specified file name
   * @param file
   * @param newFileName
   */
  private uploadFile(file: File, newFileName: string){
    this.horseService.postFile(file, newFileName).subscribe(
      () => {
        console.log("Image successfully uploaded");
      }, error => {
        this.defaultServiceErrorHandling(error)
      });
  }

  /**
   * Generates a random hex with the specified length
   * Inspired from:
   * https://stackoverflow.com/a/27747377
   * @param len
   */
  private generateHex(len: number): string {
    var arr = new Uint8Array((len) / 2)
    window.crypto.getRandomValues(arr)
    return Array.from(arr, this.dec2hex).join('')
  }

  /**
   * Converts a decimal to its hex value
   * @param dec
   */
  private dec2hex(dec: number): string {
    return ('0' + dec.toString(16)).substr(-2)
  }

Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
105 106 107 108 109 110 111 112 113 114 115 116 117 118
  private defaultServiceErrorHandling(error: any) {
    console.log(error);
    this.error = true;
    if (error.status === 0) {
      // If status is 0, the backend is probably down
      this.errorMessage = 'The backend seems not to be reachable';
    } else if (error.error.message === 'No message available') {
      // If no detailed error message is provided, fall back to the simple error name
      this.errorMessage = error.error.error;
    } else {
      this.errorMessage = error.error.message;
    }
  }
}