0

Send Queue Message

by
Published today

Send a message to a Cloudflare Queue. Set json_body for a JSON message or text_body for a plain-text one.

Script cloudflare Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 3 hours ago
1
//native
2

3
export type DynSelect_queue_id = string
4

5
// Dropdown of the account's queues, by name.
6
export async function queue_id(auth: RT.Cloudflare) {
7
  const response = await fetch(
8
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/queues`,
9
    {
10
      headers: {
11
        Authorization: `Bearer ${auth.token}`,
12
        Accept: "application/json",
13
      },
14
    }
15
  )
16
  if (!response.ok) {
17
    throw new Error(`${response.status} ${await response.text()}`)
18
  }
19
  const { result } = (await response.json()) as {
20
    result: { queue_id: string; queue_name: string }[]
21
  }
22
  return result.map((q) => ({ value: q.queue_id, label: q.queue_name }))
23
}
24

25
/**
26
 * Send Queue Message
27
 * Send a message to a Cloudflare Queue: set json_body for a JSON message or text_body for a plain-text one.
28
 */
29
export async function main(
30
  auth: RT.Cloudflare,
31
  queue_id: DynSelect_queue_id,
32
  json_body: { [key: string]: any } | undefined,
33
  text_body: string | undefined,
34
  delay_seconds: number | undefined
35
) {
36
  if ((json_body != null) === !!text_body) {
37
    throw new Error("Set exactly one of json_body or text_body")
38
  }
39
  const message =
40
    json_body != null
41
      ? { body: json_body, content_type: "json" }
42
      : { body: text_body, content_type: "text" }
43

44
  const response = await fetch(
45
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/queues/${queue_id}/messages`,
46
    {
47
      method: "POST",
48
      headers: {
49
        Authorization: `Bearer ${auth.token}`,
50
        "Content-Type": "application/json",
51
        Accept: "application/json",
52
      },
53
      body: JSON.stringify({
54
        ...message,
55
        delay_seconds: delay_seconds ?? undefined,
56
      }),
57
    }
58
  )
59

60
  if (!response.ok) {
61
    throw new Error(`${response.status} ${await response.text()}`)
62
  }
63

64
  return await response.json()
65
}
66