update SendBatch impl

This commit is contained in:
syumai 2024-11-09 23:59:48 +09:00
parent 4fa8e20a64
commit c4e9274e73
3 changed files with 11 additions and 33 deletions

View File

@ -1,7 +1,6 @@
package queues
import (
"errors"
"syscall/js"
"github.com/syumai/workers/internal/jsutil"
@ -30,23 +29,18 @@ func NewV8BatchMessage(content js.Value, opts ...SendOption) *BatchMessage {
// newBatchMessage creates a single message to be batched before sending to a queue.
func newBatchMessage(body js.Value, contentType contentType, opts ...SendOption) *BatchMessage {
options := &sendOptions{
options := sendOptions{
ContentType: contentType,
}
for _, opt := range opts {
opt(options)
opt(&options)
}
return &BatchMessage{body: body, options: options}
}
func (m *BatchMessage) toJS() (js.Value, error) {
if m == nil {
return js.Undefined(), errors.New("message is nil")
return &BatchMessage{body: body, options: &options}
}
func (m *BatchMessage) toJS() js.Value {
obj := jsutil.NewObject()
obj.Set("body", m.body)
obj.Set("options", m.options.toJS())
return obj, nil
return obj
}

View File

@ -1,7 +1,6 @@
package queues
import (
"errors"
"fmt"
"syscall/js"
@ -52,11 +51,11 @@ func (p *Producer) SendV8(content js.Value, opts ...SendOption) error {
// - https://developers.cloudflare.com/queues/configuration/javascript-apis/#producer
// - https://developers.cloudflare.com/queues/configuration/javascript-apis/#queuesendoptions
func (p *Producer) send(body js.Value, contentType contentType, opts ...SendOption) error {
options := &sendOptions{
options := sendOptions{
ContentType: contentType,
}
for _, opt := range opts {
opt(options)
opt(&options)
}
prom := p.queue.Call("send", body, options.toJS())
@ -66,29 +65,14 @@ func (p *Producer) send(body js.Value, contentType contentType, opts ...SendOpti
// SendBatch sends multiple messages to a queue. This function allows setting options for each message.
func (p *Producer) SendBatch(messages []*BatchMessage, opts ...BatchSendOption) error {
if p.queue.IsUndefined() {
return errors.New("queue object not found")
}
if len(messages) == 0 {
return nil
}
var options *batchSendOptions
if len(opts) > 0 {
options = &batchSendOptions{}
var options batchSendOptions
for _, opt := range opts {
opt(options)
}
opt(&options)
}
jsArray := jsutil.NewArray(len(messages))
for i, message := range messages {
jsValue, err := message.toJS()
if err != nil {
return fmt.Errorf("failed to convert message %d to JS: %w", i, err)
}
jsArray.SetIndex(i, jsValue)
jsArray.SetIndex(i, message.toJS())
}
prom := p.queue.Call("sendBatch", jsArray, options.toJS())