Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,20 @@ class Connection {
send (content, opts) {
if (this.state !== Connection.states().OPEN) {
return Promise.reject(new Error('instance not in state OPEN'))
} else if (typeof content !== 'string') {
return Promise.reject(new Error('first argument must be a string'))
} else if (typeof content !== 'string' && !Buffer.isBuffer(content)) {
return Promise.reject(
new Error('first argument must be a string or a Buffer')
)
}
opts = opts || {}
const terminator = opts.terminator || ''
const timeoutInit = opts.timeoutInit || 100
const timeoutRolling = opts.timeoutRolling || 10
const fixedRespBytesLength = opts.fixedRespBytesLength || -1

this.state = Connection.states().INUSE
let chunks = ''
const bytes = []
let timer

return new Promise((resolve, reject) => {
Expand All @@ -65,19 +69,23 @@ class Connection {
timer = null
}
chunks = chunks.concat(data)
bytes.push(data.toString('hex').toUpperCase())
if (terminator) {
const ix = chunks.indexOf(terminator)
if (ix > 0 && ix === chunks.length + 1) {
if (
bytes.length >= fixedRespBytesLength ||
(ix > 0 && ix === chunks.length + 1)
) {
this.state = Connection.states().OPEN
resolve(chunks)
resolve(fixedRespBytesLength > 0 ? bytes.join('') : chunks)
} else if (ix > 0 && ix !== chunks.length + 1) {
this.state = Connection.states().ERROR
reject(new Error('Terminator detected in the middle of answer. Check your options'))
this.close()
}
}
timer = setTimeout(() => {
resolve(chunks)
resolve(fixedRespBytesLength > 0 ? bytes.join('') : chunks)
}, timeoutRolling)
})

Expand All @@ -86,7 +94,7 @@ class Connection {
reject(new Error(err))
}
timer = setTimeout(() => {
resolve(chunks)
resolve(fixedRespBytesLength > 0 ? bytes.join('') : chunks)
}, timeoutInit)
})
})
Expand Down