p2p-storage-ipfs.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. console.log('storing tweet');
  13. return this.storeOnIPFS(tweet);
  14. }
  15. /**
  16. * Store public key history on ipfs
  17. * @param publicKeyHistory public key history object
  18. */
  19. public storePublicKey(publicKeyHistory) {
  20. return this.storeOnIPFS(publicKeyHistory);
  21. }
  22. private storeOnIPFS(json) {
  23. const formData = new FormData();
  24. formData.append("data", JSON.stringify(json));
  25. return this.http.post(this.infuraUrl + "add", formData).toPromise();
  26. }
  27. /**
  28. * fetch data from ipfs for hash
  29. * @param hash address hash
  30. */
  31. public async fetchJson(hash: string) {
  32. const options = {
  33. params: { arg: hash }
  34. };
  35. return await this.http.get(this.infuraUrl + "cat", options).toPromise();
  36. }
  37. /**
  38. * fetch tweet from ipfs for hash
  39. * @param hash address hash
  40. */
  41. public async fetchTweet(hash: string): Promise < string > {
  42. console.log('address hash is:', hash);
  43. let tweet;
  44. const options = {
  45. params: { arg: hash }
  46. };
  47. try {
  48. tweet = await this.http.get < string > (this.infuraUrl + "cat", options).toPromise();
  49. } catch (err) {
  50. console.log("failed to resolve get promise",err);
  51. }
  52. return tweet;
  53. }
  54. /**
  55. * fetch multiple tweets from ipfs
  56. * @param hashs array of hashes
  57. */
  58. public async fetchTweets(hashs: string[]): Promise < string[] > {
  59. return await Promise.all(hashs.map(hash => this.fetchTweet(hash)));
  60. }
  61. }