Skip to content

Commit 097532a

Browse files
committed
improved error handling + permissions in getIpfs
1 parent 3c551d7 commit 097532a

File tree

1 file changed

+41
-18
lines changed

1 file changed

+41
-18
lines changed

src/ipfs/getIpfs.js

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,20 @@
11
let ipfsInstance;
2+
const DEFAULT_PERMISSIONS = ["id", "version", "add", "cat", "dag"];
23

3-
const getIpfs = () => {
4+
export const ipfsIsWorking = async ipfs => {
5+
try {
6+
const id = await ipfs.id();
7+
if (id.id !== undefined && id.agentVersion !== undefined) {
8+
return true;
9+
} else {
10+
return false;
11+
}
12+
} catch (err) {
13+
return false;
14+
}
15+
};
16+
17+
const getIpfs = (permissions = DEFAULT_PERMISSIONS) => {
418
return new Promise(async (resolve, reject) => {
519
// if already instantiated
620
if (ipfsInstance) {
@@ -11,33 +25,42 @@ const getIpfs = () => {
1125
let ipfs = window.ipfs;
1226
if (window.ipfs.enable) {
1327
console.log("window.ipfs.enable is available!");
28+
// if user set permissions, make sure id and version are both added
29+
if (permissions.indexOf("id") < 0) {
30+
permissions.push("id");
31+
}
32+
if (permissions.indexOf("version") < 0) {
33+
permissions.push("version");
34+
}
1435
ipfs = await window.ipfs.enable({
15-
commands: ["id", "version", "add", "cat", "dag"]
36+
commands: permissions
1637
});
1738
} else {
1839
console.log("legacy window.ipfs is available!");
1940
}
20-
21-
try {
22-
const id = await ipfs.id();
23-
if (id.id !== undefined && id.agentVersion !== undefined) {
24-
ipfsInstance = ipfs;
25-
return resolve(ipfs);
26-
}
27-
} catch (err) {}
28-
console.log(
29-
"cannot access window.ipfs, may not be connected to a working gateway"
30-
);
41+
const isWorking = await ipfsIsWorking(ipfs);
42+
if (isWorking) {
43+
ipfsInstance = ipfs;
44+
resolve(ipfsInstance);
45+
} else {
46+
console.log(
47+
"cannot access window.ipfs, may not be connected to a working gateway"
48+
);
49+
}
3150
}
3251

3352
console.log("window.ipfs is not available, downloading from CDN...");
3453
const script = document.createElement("script");
3554
script.src = "https://unpkg.com/ipfs/dist/index.min.js";
36-
script.onload = () => {
37-
console.log("starting IPFS node");
38-
const ipfs = new window.Ipfs();
39-
ipfsInstance = ipfs;
40-
ipfs.once("ready", () => resolve(ipfs));
55+
script.onload = async () => {
56+
const ipfs = await window.Ipfs.create();
57+
const isWorking = await ipfsIsWorking(ipfs);
58+
if (isWorking) {
59+
ipfsInstance = ipfs;
60+
resolve(ipfsInstance);
61+
} else {
62+
reject(new Error("js-ipfs is not able to load"));
63+
}
4164
};
4265
script.onerror = reject;
4366
document.body.appendChild(script);

0 commit comments

Comments
 (0)