1
1
let ipfsInstance ;
2
+ const DEFAULT_PERMISSIONS = [ "id" , "version" , "add" , "cat" , "dag" ] ;
2
3
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 ) => {
4
18
return new Promise ( async ( resolve , reject ) => {
5
19
// if already instantiated
6
20
if ( ipfsInstance ) {
@@ -11,33 +25,42 @@ const getIpfs = () => {
11
25
let ipfs = window . ipfs ;
12
26
if ( window . ipfs . enable ) {
13
27
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
+ }
14
35
ipfs = await window . ipfs . enable ( {
15
- commands : [ "id" , "version" , "add" , "cat" , "dag" ]
36
+ commands : permissions
16
37
} ) ;
17
38
} else {
18
39
console . log ( "legacy window.ipfs is available!" ) ;
19
40
}
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
+ }
31
50
}
32
51
33
52
console . log ( "window.ipfs is not available, downloading from CDN..." ) ;
34
53
const script = document . createElement ( "script" ) ;
35
54
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
+ }
41
64
} ;
42
65
script . onerror = reject ;
43
66
document . body . appendChild ( script ) ;
0 commit comments