1
1
const CID = require ( "cids" )
2
2
3
- function ipldLoader ( ipfs , path , callback ) {
4
- let cid
5
- try {
6
- cid = new CID ( path )
7
- } catch ( e ) {
8
- callback ( e )
9
- }
10
- if ( cid . codec === "dag-cbor" || cid . codec === "dag-json" ) {
11
- ipfs . dag . get ( path , ( err , { value } ) => {
12
- if ( err ) {
13
- callback ( err )
14
- } else {
15
- callback ( null , { document : value } )
16
- }
17
- } )
3
+ async function ipldLoader ( ipfs , path ) {
4
+ const cid = new CID ( path )
5
+ if ( cid . codec === "dag-cbor" ) {
6
+ return ipfs . dag . get ( path ) . then ( ( { value } ) => ( { document : value } ) )
18
7
} else {
19
- callback ( new Error ( "Unsupported IPLD codecc" ) )
8
+ throw new Error ( "Unsupported IPLD codec" )
20
9
}
21
10
}
22
11
23
- function ipfsLoader ( ipfs , path , callback ) {
24
- ipfs . cat ( path , ( err , bytes ) => {
25
- if ( err ) {
26
- callback ( err )
27
- } else {
28
- const string = bytes . toString ( "utf8" )
29
- let value = null ,
30
- error = null
31
- try {
32
- value = { document : JSON . parse ( string ) }
33
- } catch ( e ) {
34
- error = e
35
- } finally {
36
- callback ( error , value )
37
- }
38
- }
39
- } )
12
+ function ipfsLoader ( ipfs , path ) {
13
+ return ipfs . cat ( path ) . then ( bytes => ( { document : JSON . parse ( bytes ) } ) )
40
14
}
41
15
42
16
const documentLoaders = {
@@ -47,13 +21,12 @@ const documentLoaders = {
47
21
}
48
22
49
23
const prefixes = Object . keys ( documentLoaders )
50
- const getDocumentLoader = ipfs => ( url , callback ) => {
24
+
25
+ module . exports = ipfs => async ( url , options ) => {
51
26
const prefix = prefixes . find ( prefix => url . indexOf ( prefix ) === 0 )
52
27
if ( prefix ) {
53
- documentLoaders [ prefix ] ( ipfs , url . slice ( prefix . length ) , callback )
28
+ return documentLoaders [ prefix ] ( ipfs , url . slice ( prefix . length ) )
54
29
} else {
55
- callback ( new Error ( "Could not load document" , url ) )
30
+ throw new Error ( "Could not load document" , url )
56
31
}
57
32
}
58
-
59
- module . exports = getDocumentLoader
0 commit comments