All files / app/formly/image-upload image-upload.component.ts

42.3% Statements 11/26
42.1% Branches 8/19
28.57% Functions 2/7
30% Lines 6/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 4912x             12x               12x     1x     1x 1x                                                    
import { HttpEventType } from '@angular/common/http';
import { Component, EventEmitter, Output } from '@angular/core';
import { catchError, last, map } from 'rxjs';
import { Ref } from '../../model/ref';
import { ProxyService } from '../../service/api/proxy.service';
import { Store } from '../../store/store';
import { Saving } from '../../store/submit';
import { readFileAsDataURL } from '../../util/async';
 
@Component({
  selector: 'app-image-upload',
  templateUrl: './image-upload.component.html',
  styleUrls: ['./image-upload.component.scss'],
  host: { 'class': 'form-array' }
})
export class ImageUploadComponentI {
 
  @Output()
  data = new EventEmitter<Saving | undefined | string>();
 
  constructor(
    private store: Store,
    private proxy: ProxyService,
  ) { }
 
  readImage(files?: FileList) {
    this.data.next(undefined)
    if (!files || !files.length) return;
    const file = files[0]!;
    this.data.next({ name: file.name });
    this.proxy.save(file, this.store.account.origin).pipe(
      map(event => {
        switch (event.type) {
          case HttpEventType.Response:
            return event.body;
          case HttpEventType.UploadProgress:
            const percentDone = event.total ? Math.round(100 * event.loaded / event.total) : 0;
            this.data.next({ name: file.name, progress: percentDone });
            return null;
        }
        return null;
      }),
      last(),
      map((ref: Ref | null) => ref?.url),
      catchError(err => readFileAsDataURL(file)) // base64
    ).subscribe(url => this.data.next({ url, name: file.name }));
  }
}