Skip to content

Commit

Permalink
fix: do not throw if multiaddr str is invalid, fixes multiformats#25
Browse files Browse the repository at this point in the history
  • Loading branch information
mkg20001 committed Jan 17, 2019
1 parent 0dc5286 commit a5ef750
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 19 deletions.
36 changes: 17 additions & 19 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,20 +129,25 @@ exports.IPFS = IPFS
* Validation funcs
*/

function and () {
const args = Array.from(arguments)

function matches (a) {
function makeMatchesFunction (partialMatch) {
return function matches (a) {
if (typeof a === 'string') {
a = multiaddr(a)
try {
a = multiaddr(a)
} catch (err) { // catch error
return false // also if it's invalid it's propably not matching as well so return false
}
}
let out = partialMatch(a.protoNames())
if (out === null) {
return false
}
return out.length === 0
}
}

function and () {
const args = Array.from(arguments)
function partialMatch (a) {
if (a.length < args.length) {
return null
Expand All @@ -163,25 +168,14 @@ function and () {
return {
toString: function () { return '{ ' + args.join(' ') + ' }' },
input: args,
matches: matches,
matches: makeMatchesFunction(partialMatch),
partialMatch: partialMatch
}
}

function or () {
const args = Array.from(arguments)

function matches (a) {
if (typeof a === 'string') {
a = multiaddr(a)
}
const out = partialMatch(a.protoNames())
if (out === null) {
return false
}
return out.length === 0
}

function partialMatch (a) {
let out = null
args.some((arg) => {
Expand All @@ -200,7 +194,7 @@ function or () {
const result = {
toString: function () { return '{ ' + args.join(' ') + ' }' },
input: args,
matches: matches,
matches: makeMatchesFunction(partialMatch),
partialMatch: partialMatch
}

Expand All @@ -212,7 +206,11 @@ function base (n) {

function matches (a) {
if (typeof a === 'string') {
a = multiaddr(a)
try {
a = multiaddr(a)
} catch (err) { // catch error
return false // also if it's invalid it's propably not matching as well so return false
}
}

const pnames = a.protoNames()
Expand Down
4 changes: 4 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@ describe('multiaddr validation', function () {
})
}

it('do not throw if multiaddr str is invalid', function () {
expect(mafmt.HTTP.matches('/http-google-com')).to.be.eql(false)
})

it('DNS validation', function () {
assertMatches(mafmt.DNS, goodDNS)
assertMismatches(mafmt.DNS, badDNS, badIP)
Expand Down

0 comments on commit a5ef750

Please sign in to comment.