Skip to content

Commit

Permalink
Merge pull request #685 from tulios/fix-encoder-instanceof-issue
Browse files Browse the repository at this point in the history
Fix encoder instanceof issue with Encoder
  • Loading branch information
Nevon authored Apr 29, 2020
2 parents 9b65843 + 5d69c08 commit cfbb49d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/protocol/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,15 +173,15 @@ module.exports = class Encoder {
}

writeEncoder(value) {
if (value instanceof Encoder !== true) {
if (value == null || value.buffer == null) {
throw new Error('value should be an instance of Encoder')
}
this.buffer = Buffer.concat([this.buffer, value.buffer])
return this

return this.writeBuffer(value.buffer)
}

writeEncoderArray(value) {
if (!Array.isArray(value) || value.some(v => !(v instanceof Encoder))) {
if (!Array.isArray(value) || value.some(v => v == null || !Buffer.isBuffer(v.buffer))) {
throw new Error('all values should be an instance of Encoder[]')
}

Expand All @@ -194,7 +194,7 @@ module.exports = class Encoder {
}

writeBuffer(value) {
if (value instanceof Buffer !== true) {
if (!Buffer.isBuffer(value)) {
throw new Error('value should be an instance of Buffer')
}

Expand Down
31 changes: 31 additions & 0 deletions src/protocol/encoder.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,37 @@ describe('Protocol > Encoder', () => {
const B = (...args) => Buffer.from(args)
const L = value => Long.fromString(`${value}`)

describe('writeEncoder', () => {
it('should throw if the value is not an Encoder', () => {
const encoder = new Encoder()
expect(() => encoder.writeEncoder()).toThrow('value should be an instance of Encoder')
})

it('should append the value buffer to the existing encoder', () => {
const encoder = new Encoder().writeBuffer(B(1)).writeEncoder(new Encoder().writeBuffer(B(2)))
expect(encoder.buffer).toEqual(B(1, 2))
})
})

describe('writeEncoderArray', () => {
it('should throw if any of the elements in the array are not encoders', () => {
const values = [new Encoder(), 'not an encoder']
expect(() => new Encoder().writeEncoderArray(values)).toThrow(
'all values should be an instance of Encoder[]'
)
})

it('should append all encoder values to the existing encoder', () => {
const values = [
new Encoder().writeBuffer(B(1)),
new Encoder().writeBuffer(B(2)),
new Encoder().writeBuffer(B(3)),
]

expect(new Encoder().writeEncoderArray(values).buffer).toEqual(B(1, 2, 3))
})
})

describe('varint', () => {
test('encode signed int32 numbers', () => {
expect(signed32(0)).toEqual(B(0x00))
Expand Down

0 comments on commit cfbb49d

Please sign in to comment.