1
1
'use strict'
2
2
3
3
const Joi = require ( 'joi' )
4
+ const {
5
+ PassThrough
6
+ } = require ( 'stream' )
7
+
8
+ const mapEntry = ( entry ) => {
9
+ return {
10
+ Name : entry . name ,
11
+ Type : entry . type ,
12
+ Size : entry . size ,
13
+ Hash : entry . hash
14
+ }
15
+ }
4
16
5
17
const mfsLs = ( api ) => {
6
18
api . route ( {
@@ -14,21 +26,59 @@ const mfsLs = (api) => {
14
26
const {
15
27
arg,
16
28
long,
17
- cidBase
29
+ cidBase,
30
+ stream
18
31
} = request . query
19
32
33
+ if ( stream ) {
34
+ const readableStream = ipfs . files . lsReadableStream ( arg , {
35
+ long,
36
+ cidBase
37
+ } )
38
+
39
+ if ( ! readableStream . _read ) {
40
+ // make the stream look like a Streams2 to appease Hapi
41
+ readableStream . _read = ( ) => { }
42
+ readableStream . _readableState = { }
43
+ }
44
+
45
+ let passThrough
46
+
47
+ readableStream . on ( 'data' , ( entry ) => {
48
+ if ( ! passThrough ) {
49
+ passThrough = new PassThrough ( )
50
+
51
+ reply ( passThrough )
52
+ . header ( 'X-Stream-Output' , '1' )
53
+ }
54
+
55
+ passThrough . write ( JSON . stringify ( mapEntry ( entry ) ) + '\n' )
56
+ } )
57
+
58
+ readableStream . once ( 'end' , ( entry ) => {
59
+ if ( passThrough ) {
60
+ passThrough . end ( entry ? JSON . stringify ( mapEntry ( entry ) ) + '\n' : undefined )
61
+ }
62
+ } )
63
+
64
+ readableStream . once ( 'error' , ( error ) => {
65
+ reply ( {
66
+ Message : error . message ,
67
+ Code : error . code || 0 ,
68
+ Type : 'error'
69
+ } ) . code ( 500 ) . takeover ( )
70
+ } )
71
+
72
+ return
73
+ }
74
+
20
75
return ipfs . files . ls ( arg , {
21
76
long,
22
77
cidBase
23
78
} )
24
79
. then ( files => {
25
80
reply ( {
26
- Entries : files . map ( file => ( {
27
- Name : file . name ,
28
- Type : file . type ,
29
- Size : file . size ,
30
- Hash : file . hash
31
- } ) )
81
+ Entries : files . map ( mapEntry )
32
82
} )
33
83
} )
34
84
. catch ( error => {
@@ -47,12 +97,17 @@ const mfsLs = (api) => {
47
97
query : Joi . object ( ) . keys ( {
48
98
arg : Joi . string ( ) . default ( '/' ) ,
49
99
long : Joi . boolean ( ) . default ( false ) ,
50
- cidBase : Joi . string ( ) . default ( 'base58btc' )
100
+ cidBase : Joi . string ( ) . default ( 'base58btc' ) ,
101
+ stream : Joi . boolean ( ) . default ( false )
51
102
} )
52
103
. rename ( 'l' , 'long' , {
53
104
override : true ,
54
105
ignoreUndefined : true
55
106
} )
107
+ . rename ( 's' , 'stream' , {
108
+ override : true ,
109
+ ignoreUndefined : true
110
+ } )
56
111
}
57
112
}
58
113
} )
0 commit comments