53 lines
1.7 KiB
Go
Raw Normal View History

2024-11-09 17:59:56 +09:00
package queues
import (
"syscall/js"
"github.com/syumai/workers/internal/jsutil"
)
2025-01-15 21:09:14 +09:00
// FIXME: rename to MessageSendRequest
// see: https://developers.cloudflare.com/queues/configuration/javascript-apis/#messagesendrequest
2024-11-09 17:59:56 +09:00
type BatchMessage struct {
2024-11-09 23:49:32 +09:00
body js.Value
2024-11-09 17:59:56 +09:00
options *sendOptions
}
2024-11-10 00:30:01 +09:00
// NewTextBatchMessage creates a single text message to be batched before sending to a queue.
2024-11-09 23:49:32 +09:00
func NewTextBatchMessage(content string, opts ...SendOption) *BatchMessage {
return newBatchMessage(js.ValueOf(content), contentTypeText, opts...)
}
2024-11-10 00:30:01 +09:00
// NewBytesBatchMessage creates a single byte array message to be batched before sending to a queue.
2024-11-09 23:49:32 +09:00
func NewBytesBatchMessage(content []byte, opts ...SendOption) *BatchMessage {
return newBatchMessage(js.ValueOf(content), contentTypeBytes, opts...)
}
2024-11-10 00:30:01 +09:00
// NewJSONBatchMessage creates a single JSON message to be batched before sending to a queue.
2024-11-09 23:49:32 +09:00
func NewJSONBatchMessage(content any, opts ...SendOption) *BatchMessage {
return newBatchMessage(js.ValueOf(content), contentTypeJSON, opts...)
}
2024-11-10 00:30:01 +09:00
// NewV8BatchMessage creates a single raw JS value message to be batched before sending to a queue.
2024-11-09 23:49:32 +09:00
func NewV8BatchMessage(content js.Value, opts ...SendOption) *BatchMessage {
return newBatchMessage(content, contentTypeV8, opts...)
}
// newBatchMessage creates a single message to be batched before sending to a queue.
func newBatchMessage(body js.Value, contentType contentType, opts ...SendOption) *BatchMessage {
2024-11-09 23:59:48 +09:00
options := sendOptions{
2024-11-09 23:49:32 +09:00
ContentType: contentType,
}
2024-11-09 17:59:56 +09:00
for _, opt := range opts {
2024-11-09 23:59:48 +09:00
opt(&options)
2024-11-09 17:59:56 +09:00
}
2024-11-09 23:59:48 +09:00
return &BatchMessage{body: body, options: &options}
2024-11-09 17:59:56 +09:00
}
2024-11-09 23:59:48 +09:00
func (m *BatchMessage) toJS() js.Value {
2024-11-09 17:59:56 +09:00
obj := jsutil.NewObject()
2024-11-09 23:49:32 +09:00
obj.Set("body", m.body)
2024-11-09 17:59:56 +09:00
obj.Set("options", m.options.toJS())
2024-11-09 23:59:48 +09:00
return obj
2024-11-09 17:59:56 +09:00
}