Last active
June 7, 2019 18:19
-
-
Save alexytiger/f7c260f6ae7f042b82f8d5d35c7c30c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, Inject } from '@angular/core'; | |
import { HttpClient } from '@angular/common/http'; | |
import { Observable, from, empty } from 'rxjs'; | |
import { switchMap, map, tap } from 'rxjs/operators'; | |
import { ipfsToken } from './tokens'; | |
import { Buffer } from 'buffer'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class IpfsDaemonService { | |
constructor(@Inject(ipfsToken) private ipfs, | |
private httpClient: HttpClient) {} | |
public addFile(file: File): Observable<string> { | |
const data = { | |
path: file.name, | |
content: file | |
} | |
const options = { | |
progress: (prog) => console.log(`progress report: ${prog}`) | |
}; | |
return from(this.ipfs.add(data, options)).pipe( | |
tap((res: any) => | |
console.log(`IPFS node response json: ${JSON.stringify(res)}`) | |
), | |
map((res: any) => res[res.length - 1].hash ) | |
); | |
} | |
public getFile = (hash: string): Observable<Blob> => | |
from(this.ipfs.cat(hash)).pipe( | |
switchMap((buffer: Buffer) => { | |
const byteString = buffer.toString('base64'); | |
const url = `data:application/octet-stream;base64,${byteString}`; | |
return this.httpClient.get(url, { | |
responseType: 'blob' | |
}); | |
} | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment