cloudflare / cloudflare/workerd

Support discriminated unions for queue message batches

Open
#2,795 1 comment 4 reactions 1 assignee Claimed by @workers-devprod View on GitHub
types
Dominant language
C++
Stars
8.7k
Forks
739
Avg merge
2d 20h
Merged PRs (30d)
174

Description

When a worker is a consumer for multiple queues its not possible with the existing types to make the message body type depend on the name of the queue.

Changing the queue name to be generic would allow creating a discriminated union type for different message batches

```diff
- export interface MessageBatch {
+ export interface MessageBatch {
readonly messages: readonly Message[];
- readonly queue: string;
+ readonly queue: Name;
retryAll(options?: QueueRetryOptions): void;
ackAll(): void;
}
```

Which then enables:

```js
type Batch =
| MessageBatch<{ foo: number }, "queue-1">
| MessageBatch<{ bar: number }, "queue-2">

export default class extends WorkerEntrypoint {
async queue(_batch: Batch) {
switch (batch.queue) {
case "queue-1": {
// message.body is typed as { foo: number } here
break;
}
case "queue-2": {
// message.body is typed as { bar: number } here
break;
}
}
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.