@@ -7,35 +7,36 @@ const getConfig = require('./utils/default-config')
7
7
const sendRequest = require ( './utils/send-request' )
8
8
9
9
function ipfsClient ( hostOrMultiaddr , port , opts ) {
10
- const config = getConfig ( )
11
- if ( typeof hostOrMultiaddr === 'string' ) {
10
+ // convert all three params to objects that we can merge.
11
+ let hostAndPort = { }
12
+
13
+ if ( hostOrMultiaddr . host ) {
14
+ hostAndPort = hostOrMultiaddr
15
+
16
+ } else if ( multiaddr . isMultiaddr ( hostOrMultiaddr ) ) {
17
+ hostAndPort = toHostAndPort ( hostOrMultiaddr )
18
+
19
+ } else if ( typeof hostOrMultiaddr === 'string' ) {
12
20
if ( hostOrMultiaddr [ 0 ] === '/' ) {
13
21
// throws if multiaddr is malformed or can't be converted to a nodeAddress
14
- const maddr = multiaddr ( hostOrMultiaddr ) . nodeAddress ( )
15
- config . host = maddr . address
16
- config . port = maddr . port
22
+ hostAndPort = toHostAndPort ( multiaddr ( hostOrMultiaddr ) )
17
23
} else {
18
- config . host = hostOrMultiaddr
19
- config . port = port && typeof port !== 'object' ? port : config . port
24
+ // hostAndPort is domain or ip address as a string
25
+ hostAndPort = hostOrMultiaddr
20
26
}
21
- }
22
27
23
- let lastIndex = arguments . length
24
- while ( ! opts && lastIndex -- > 0 ) {
25
- opts = arguments [ lastIndex ]
26
- if ( opts ) break
28
+ // autoconfigure host and port in browser
29
+ } else if ( ! hostOrMultiaddr && typeof self !== 'undefined' ) {
30
+ const split = self . location . host . split ( ':' )
31
+ hostAndPort . host = split [ 0 ]
32
+ hostAndPort . port = split [ 1 ]
27
33
}
28
34
29
- Object . assign ( config , opts )
30
-
31
- // autoconfigure in browser
32
- if ( ! config . host &&
33
- typeof self !== 'undefined' ) {
34
- const split = self . location . host . split ( ':' )
35
- config . host = split [ 0 ]
36
- config . port = split [ 1 ]
35
+ if ( port && typeof port !== 'object' ) {
36
+ port = { port : port }
37
37
}
38
38
39
+ const config = Object . assign ( getConfig ( ) , hostAndPort , port , opts )
39
40
const requestAPI = sendRequest ( config )
40
41
const cmds = loadCommands ( requestAPI , config )
41
42
cmds . send = requestAPI
@@ -44,4 +45,13 @@ function ipfsClient (hostOrMultiaddr, port, opts) {
44
45
return cmds
45
46
}
46
47
48
+ // throws if multiaddr can't be converted to a nodeAddress
49
+ function toHostAndPort ( multiaddr ) {
50
+ const nodeAddr = multiaddr . nodeAddress ( )
51
+ return {
52
+ host : nodeAddr . address ,
53
+ port : nodeAddr . port
54
+ }
55
+ }
56
+
47
57
module . exports = ipfsClient
0 commit comments