All files / app/core/services/ipfs ipfs-client.service.ts

51.78% Statements 29/56
68.75% Branches 11/16
40.74% Functions 11/27
56% Lines 28/50

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 49 50 51 52 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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157                  1x         46x     46x     46x   42x 4x   2x     2x   2x         6x       6x 6x 6x   6x             1x             4x 4x               2x   1x         1x               1x 1x                                                                                               2x 2x           1x   1x 1x                           1x    
import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError, of } from 'rxjs';
import { map, catchError, timeout } from 'rxjs/operators';
import { IIPFSClient } from './ipfs-client.interface';
import { IPFSConfig, IPFSUploadResult } from '../../domain/interfaces/ipfs.interface';
import { IPFS_CONFIG } from './ipfs-storage.service';
 
@Injectable()
export class IPFSClient implements IIPFSClient {
  private config: IPFSConfig;
  private baseUrl: string;
 
  constructor(
    private http: HttpClient,
    @Inject(IPFS_CONFIG) config: IPFSConfig
  ) {
    this.config = config;
    
    // Validate configuration
    if (config.mode === 'api') {
      // API mode can use proxy (empty apiEndpoint) or explicit endpoint
      this.baseUrl = config.apiEndpoint ? config.apiEndpoint + '/api/v0' : '/api/v0';
    } else if (config.mode === 'gateway') {
      // Gateway mode - read only
      Iif (!config.gateway) {
        throw new Error('Invalid IPFS configuration: gateway URL required for gateway mode');
      }
      this.baseUrl = config.gateway;
    } else {
      throw new Error('Invalid IPFS configuration: unsupported mode');
    }
  }
 
  add(data: Uint8Array): Observable<IPFSUploadResult> {
    Iif (this.config.mode === 'gateway') {
      return throwError(() => new Error('Gateway mode does not support uploads'));
    }
 
    const formData = new FormData();
    const blob = new Blob([data], { type: 'application/octet-stream' });
    formData.append('file', blob);
 
    return this.http.post<any>(`${this.baseUrl}/add`, formData, {
      params: { pin: 'true' },
      headers: {
        // Let browser handle Content-Type for FormData
      }
    }).pipe(
      timeout(this.config.timeout),
      map(response => ({
        cid: response.Hash,
        size: response.Size || data.length,
        timestamp: new Date(),
        pinned: true
      })),
      catchError(error => {
        console.error('IPFS add failed:', error);
        return throwError(() => new Error(`Failed to add to IPFS: ${error.message}`));
      })
    );
  }
 
  get(cid: string): Observable<Uint8Array> {
    let url: string;
    
    if (this.config.mode === 'api') {
      // Use API endpoint
      return this.http.post(`${this.baseUrl}/cat`, null, {
        params: { arg: cid },
        responseType: 'arraybuffer'
      }).pipe(
        timeout(this.config.timeout),
        map(buffer => new Uint8Array(buffer)),
        catchError(error => {
          console.error('IPFS get failed:', error);
          return throwError(() => new Error(`Failed to get from IPFS: ${error.message}`));
        })
      );
    } else {
      // Use gateway
      url = `${this.config.gateway}/ipfs/${cid}`;
      return this.http.get(url, {
        responseType: 'arraybuffer'
      }).pipe(
        timeout(this.config.timeout),
        map(buffer => new Uint8Array(buffer)),
        catchError(error => {
          console.error('IPFS gateway get failed:', error);
          return throwError(() => new Error(`Failed to get from IPFS gateway: ${error.message}`));
        })
      );
    }
  }
 
  pin(cid: string): Observable<boolean> {
    Iif (this.config.mode === 'gateway') {
      return throwError(() => new Error('Gateway mode does not support pinning'));
    }
 
    return this.http.post<any>(`${this.baseUrl}/pin/add`, null, {
      params: { arg: cid }
    }).pipe(
      timeout(this.config.timeout),
      map(() => true),
      catchError(error => {
        console.error('IPFS pin failed:', error);
        return of(false);
      })
    );
  }
 
  unpin(cid: string): Observable<boolean> {
    Iif (this.config.mode === 'gateway') {
      return throwError(() => new Error('Gateway mode does not support unpinning'));
    }
 
    return this.http.post<any>(`${this.baseUrl}/pin/rm`, null, {
      params: { arg: cid }
    }).pipe(
      timeout(this.config.timeout),
      map(() => true),
      catchError(error => {
        console.error('IPFS unpin failed:', error);
        return of(false);
      })
    );
  }
 
  isHealthy(): Observable<boolean> {
    if (this.config.mode === 'api') {
      return this.http.post<any>(`${this.baseUrl}/version`, null, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).pipe(
        timeout(5000),
        map(() => true),
        catchError((error) => {
          console.error('IPFS health check failed:', error);
          return of(false);
        })
      );
    } else E{
      // For gateway, just check if we can reach it
      return this.http.head(this.config.gateway).pipe(
        timeout(5000),
        map(() => true),
        catchError(() => of(false))
      );
    }
  }
 
  getType(): string {
    return this.config.mode;
  }
}