UNPKG

3.2 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.IpfsService = exports.IpfsContentFormat = void 0;
4var IpfsContentFormat;
5(function (IpfsContentFormat) {
6 IpfsContentFormat["FormData"] = "formdata";
7 IpfsContentFormat["ArrayBuffer"] = "arraybuffer";
8 IpfsContentFormat["Blob"] = "blob";
9 IpfsContentFormat["Text"] = "text";
10 IpfsContentFormat["JSON"] = "json";
11})(IpfsContentFormat || (exports.IpfsContentFormat = IpfsContentFormat = {}));
12class IpfsService {
13 constructor(client) {
14 this.client = client;
15 this.upload = async (obj) => {
16 try {
17 let blob = new Blob([JSON.stringify(obj)], { type: 'application/json' });
18 const formData = new FormData();
19 formData.append('file', blob);
20 if (blob.size > 1024 * 1024 * 10) {
21 throw new Error('File too large, max file size is: 10MB');
22 }
23 else {
24 const requestOptions = {
25 method: 'POST',
26 body: formData,
27 };
28 const response = await this.client.fetchProvider.fetch(`${this.client.config.ipfsEndpoint}/api/v0/add?pin=true`, requestOptions);
29 if (!response.ok) {
30 const errorText = await response.text();
31 throw new Error(`Error in IPFS upload: ${errorText}`);
32 }
33 else {
34 const json = await response.json();
35 return json.Hash;
36 }
37 }
38 }
39 catch (error) {
40 throw new Error(error);
41 }
42 };
43 /**
44 * Get IPFS Content in JSON, without caching, to be in getIpfsContent.
45 * @param {string} hash - hash of the IPFS content you want to fetch
46 * @param {IpfsContentFormat} format - format of the content you are fetching,
47 * @returns content of the ipfs hash in your preferred format
48 */
49 this.fetch = async (hash, ipfsContentForm = IpfsContentFormat.JSON) => {
50 try {
51 let data;
52 data = await this.client.fetchProvider.fetch(`${this.client.config.ipfsEndpoint}/ipfs/${hash}`);
53 // Return the IPFS content in the format you want
54 switch (ipfsContentForm) {
55 case IpfsContentFormat.FormData:
56 return data.formData();
57 case IpfsContentFormat.ArrayBuffer:
58 return data.arrayBuffer();
59 case IpfsContentFormat.Blob:
60 return data.blob();
61 case IpfsContentFormat.Text:
62 return data.text();
63 case IpfsContentFormat.JSON:
64 return await data.json();
65 default:
66 return data;
67 }
68 }
69 catch (error) {
70 console.error(error);
71 }
72 };
73 }
74}
75exports.IpfsService = IpfsService;
76//# sourceMappingURL=ipfs.js.map
\No newline at end of file