Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(cli): support pub multiple lines on pipeline #1823

Merged
merged 1 commit into from
Dec 5, 2024
Merged
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
53 changes: 49 additions & 4 deletions cli/src/lib/pub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,46 @@ const multiSend = (
})
}

const handlePipedMultiline = (connOpts: IClientOptions, pubOpts: { topic: string; opts: IClientPublishOptions }) => {
const client = mqtt.connect(connOpts)
let messageQueue: string[] = []
let publishedCount = 0

process.stdin.pipe(split2()).on('data', (chunk) => {
const message = chunk.toString()
if (message.length > 0) {
messageQueue.push(message)
}
})

client.on('connect', () => {
basicLog.connected()
if (messageQueue.length > 0) {
logWrapper.await(`Publishing ${messageQueue.length} messages...`)
messageQueue.forEach((message) => {
client.publish(pubOpts.topic, Buffer.from(message), pubOpts.opts, (err) => {
if (err) {
basicLog.error(err)
} else {
publishedCount++
if (publishedCount === messageQueue.length) {
logWrapper.success(`Successfully published ${publishedCount} messages`)
}
}
})
})
setTimeout(() => {
client.end()
}, 1000)
}
})

client.on('error', (err) => {
basicLog.error(err)
client.end()
})
}

const handleFileRead = (filePath: string) => {
try {
basicLog.fileReading()
Expand Down Expand Up @@ -231,16 +271,21 @@ const pub = (options: PublishOptions) => {
const pubOpts = parsePublishOptions(options)

const handleStdin = () => {
if (options.multiline) {
multiSend(loadOptions, connOpts, pubOpts, options.maximumReconnectTimes)
} else {
process.stdin.pipe(
// One line mode
if (!options.multiline) {
return process.stdin.pipe(
concat((data) => {
pubOpts.message = data
send(loadOptions, connOpts, pubOpts, options.maximumReconnectTimes)
}),
)
}

// Multiline mode
const isPiped = !process.stdin.isTTY
return isPiped
? handlePipedMultiline(connOpts, pubOpts)
: multiSend(loadOptions, connOpts, pubOpts, options.maximumReconnectTimes)
}

if (options.fileRead) {
Expand Down