p2p-storage-ipfs.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { HttpClient } from "@angular/common/http";
  2. import { Injectable } from "@angular/core";
  3. @Injectable()
  4. export class P2pStorageIpfsProvider {
  5. private infuraUrl = "https://ipfs.infura.io:5001/api/v0/";
  6. constructor(public http: HttpClient) {}
  7. /**
  8. * Store private tweet on ipfs
  9. * @param tweet tweet object
  10. */
  11. public storeTweet(tweet) {
  12. return this.storeOnIPFS(tweet);
  13. }
  14. /**
  15. * Store public key history on ipfs
  16. * @param publicKeyHistory public key history object
  17. */
  18. public storePublicKey(publicKeyHistory) {
  19. return this.storeOnIPFS(publicKeyHistory);
  20. }
  21. private storeOnIPFS(json) {
  22. const formData = new FormData();
  23. formData.append("data", JSON.stringify(json));
  24. return this.http.post(this.infuraUrl + "add", formData).toPromise();
  25. }
  26. /**
  27. * fetch data from ipfs for hash
  28. * @param hash address hash
  29. */
  30. public async fetchJson(hash: string) {
  31. const options = {
  32. params: { arg: hash }
  33. };
  34. return await this.http.get(this.infuraUrl + "cat", options).toPromise();
  35. }
  36. /**
  37. * fetch tweet from ipfs for hash
  38. * @param hash address hash
  39. */
  40. public fetchTweet(hash: string): Promise<string> {
  41. const options = {
  42. params: { arg: hash }
  43. };
  44. return this.http.get<string>(this.infuraUrl + "cat", options).toPromise();
  45. }
  46. /**
  47. * fetch multiple tweets from ipfs
  48. * @param hashs array of hashes
  49. */
  50. public async fetchTweets(hashs: string[]): Promise<string[]> {
  51. return await Promise.all(hashs.map(hash => this.fetchTweet(hash)));
  52. }
  53. }