Skip to content

Commit ce0d572

Browse files
authored
Create ipfsUtils.js
1 parent 2eb3e87 commit ce0d572

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

scripts/utils/ipfsUtils.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// scripts/utils/ipfsUtils.js
2+
3+
const { create } = require('ipfs-http-client');
4+
5+
// Initialize IPFS client
6+
const ipfs = create({ url: 'https://ipfs.infura.io:5001' });
7+
8+
/**
9+
* Store data on IPFS
10+
* @param {Object} data - The data to be stored on IPFS
11+
* @returns {Promise<string>} - The CID of the stored data
12+
*/
13+
async function storeData(data) {
14+
try {
15+
const { cid } = await ipfs.add(JSON.stringify(data));
16+
console.log(`Data stored on IPFS with CID: ${cid}`);
17+
return cid.toString();
18+
} catch (error) {
19+
console.error('Error storing data on IPFS:', error);
20+
throw error;
21+
}
22+
}
23+
24+
/**
25+
* Retrieve data from IPFS
26+
* @param {string} cid - The CID of the data to retrieve
27+
* @returns {Promise<Object>} - The retrieved data
28+
*/
29+
async function retrieveData(cid) {
30+
try {
31+
const stream = ipfs.cat(cid);
32+
let data = '';
33+
34+
for await (const chunk of stream) {
35+
data += chunk.toString();
36+
}
37+
38+
console.log(`Data retrieved from IPFS with CID: ${cid}`);
39+
return JSON.parse(data);
40+
} catch (error) {
41+
console.error('Error retrieving data from IPFS:', error);
42+
throw error;
43+
}
44+
}
45+
46+
/**
47+
* Delete data from IPFS (Note: IPFS is a decentralized storage system, so data cannot be deleted)
48+
* This function is a placeholder to indicate that data cannot be deleted from IPFS.
49+
*/
50+
function deleteData() {
51+
console.warn('Data cannot be deleted from IPFS. Once stored, it remains available.');
52+
}
53+
54+
module.exports = {
55+
storeData,
56+
retrieveData,
57+
deleteData,
58+
};

0 commit comments

Comments
 (0)