From 218e1e69af630a5bfc48223d25e0a7f615cb8063 Mon Sep 17 00:00:00 2001 From: Vasco Santos Date: Thu, 19 Apr 2018 11:49:56 +0100 Subject: [PATCH] fix: Support api endpoint with no port defined --- package.json | 1 + src/index.js | 15 ++++++++++++++- test/constructor.spec.js | 6 ++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 0ac5c5b58..36fe09e84 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ "detect-node": "^2.0.3", "flatmap": "0.0.3", "glob": "^7.1.2", + "ip-regex": "^3.0.0", "ipfs-block": "~0.7.1", "ipfs-unixfs": "~0.1.14", "ipld-dag-cbor": "~0.12.0", diff --git a/src/index.js b/src/index.js index f0f73b782..74d54db5d 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,6 @@ 'use strict' +const ipRegex = require('ip-regex') const multiaddr = require('multiaddr') const loadCommands = require('./utils/load-commands') const getConfig = require('./utils/default-config') @@ -15,7 +16,19 @@ function IpfsAPI (hostOrMultiaddr, port, opts) { } catch (e) { if (typeof hostOrMultiaddr === 'string') { config.host = hostOrMultiaddr - config.port = port && typeof port !== 'object' ? port : config.port + const addrParts = hostOrMultiaddr.split(':') + if (addrParts.length === 1 && ipRegex.v4({ exact: true }).test(addrParts[0]) && + (!port || typeof port === 'object')) { + // IPv4 Host with no port specified + config.port = undefined + } else if (addrParts.length === 2 && ipRegex.v4({ exact: true }).test(addrParts[0]) && + (!port || typeof port === 'object')) { + // IPv4 Host with port specified + config.host = addrParts[0] + config.port = addrParts[1] + } else { + config.port = port + } } } diff --git a/test/constructor.spec.js b/test/constructor.spec.js index fb8b6ca23..19f7ae5c0 100644 --- a/test/constructor.spec.js +++ b/test/constructor.spec.js @@ -50,6 +50,12 @@ describe('ipfs-api constructor tests', () => { clientWorks(ipfsAPI(apiAddr, { protocol: 'http' }), done) }) + it('host:port', (done) => { + const splitted = apiAddr.split('/') + + clientWorks(ipfsAPI(`${splitted[2]}:${splitted[4]}`), done) + }) + it('host, port', (done) => { const splitted = apiAddr.split('/')