Skip to content

Commit

Permalink
fix: throw error instead of returning undefined
Browse files Browse the repository at this point in the history
`rmPrefix()` now throws an error if the given code wasn't found.
This should make increase the usability of this module.
  • Loading branch information
vmx authored and hacdias committed May 30, 2018
1 parent 46e0e02 commit 9859a71
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ exports.rmPrefix = (data) => {
exports.getCodec = (prefixedData) => {
const code = util.varintBufferDecode(prefixedData)
const codecName = codeToCodecName[code.toString('hex')]
if (codecName === undefined) {
throw new Error('Code `0x' + code.toString('hex') + '` not found')
}
return codecName
}

Expand Down
12 changes: 12 additions & 0 deletions test/multicodec.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,16 @@ describe('multicodec', () => {
'Codec `this-codec-doesnt-exist` not found'
)
})

it('throws error on unknown codec name when getting the codec', () => {
const code = Buffer.from('ffee', 'hex')

const buf = Buffer.from('hey')
const prefixedBuf = multicodec.addPrefix(code, buf)
expect(() => {
multicodec.getCodec(prefixedBuf)
}).to.throw(
'Code `0xffee` not found'
)
})
})

0 comments on commit 9859a71

Please sign in to comment.