import { Injectable } from '@angular/core' ; import { AttachmentApiService , UploadEvent , UploadEventType , } from '../../../common/api/attachment-api.service' ; import { of , OperatorFunction } from 'rxjs' ; import { catchError , last , map , switchAll , tap } from 'rxjs/operators' ; /**
 * Attachment types
 */ export type AttachmentType = 'image' | 'video' ; /**
 * Attachments
 */ export interface Attachment { type : AttachmentType ; guid : string ; } @ Injectable ( ) export class AttachmentService { param attachmentApi constructor ( protected attachmentApi ) { } param metadataFn param progressFn param errorFn resolve ( metadataFn , progressFn ? , errorFn ? ) { return input$ => input$ . pipe ( map ( file => { if ( ! file ) { return of ( null ) ; } else if ( ! ( file instanceof File ) ) { return of ( { type : UploadEventType . Success , payload : { request : { type : file . type } , response : { guid : file . guid } , } , } ) ; } const metadata = metadataFn ? metadataFn ( ) : { } ; return this . attachmentApi . upload ( file , { container_guid : metadata . containerGuid || null } ) . pipe ( tap ( uploadEvent => { if ( ! progressFn ) { return ; } if ( ! uploadEvent ) { progressFn ( false , 0 ) ; return ; } switch ( uploadEvent . type ) { case UploadEventType . Progress : progressFn ( true , uploadEvent . payload . progress ) ; break ; case UploadEventType . Fail : throw new Error ( uploadEvent . payload . response ) ; default : progressFn ( false , 0 ) ; break ; } } ) , catchError ( e => { if ( errorFn ) { errorFn ( e ) ; } return of ( null ) ; } ) , last ( ) ) ; } ) , switchAll ( ) , map ( ( uploadEvent ) => uploadEvent ? { type : uploadEvent . payload . request . type as AttachmentType , guid : uploadEvent . payload . response . guid , } : null ) ) ; } param guid prune ( guid ) { if ( ! guid ) { return Promise . resolve ( true ) ; } return this . attachmentApi . remove ( guid ) . toPromise ( ) ; } }