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

Support discriminated unions for queue message batches #2795

Open
cloudkite opened this issue Sep 24, 2024 · 0 comments
Open

Support discriminated unions for queue message batches #2795

cloudkite opened this issue Sep 24, 2024 · 0 comments
Assignees
Labels
types Related to @cloudflare/workers-types

Comments

@cloudkite
Copy link

cloudkite commented Sep 24, 2024

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

- export interface MessageBatch<Body = unknown> {
+ export interface MessageBatch<Body = unknown, Name = string> {
   readonly messages: readonly Message<Body>[];
-  readonly queue: string;
+  readonly queue: Name;
   retryAll(options?: QueueRetryOptions): void;
   ackAll(): void;
 }

Which then enables:

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;
        }
    }
  }
}
@cloudkite cloudkite added the types Related to @cloudflare/workers-types label Sep 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
types Related to @cloudflare/workers-types
Projects
Status: Backlog
Development

No branches or pull requests

2 participants