1 | import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs" |
2 |
|
3 | |
4 | * Publish message |
5 | * Send one message to an SQS queue. A string payload is sent as-is, anything else as JSON; message attribute values are sent as strings. FIFO queues need message_group_id, and message_deduplication_id unless content-based deduplication is on. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Aws, |
9 | queue_url: string, |
10 | payload: any, |
11 | message_attributes: { [key: string]: string } | undefined, |
12 | message_group_id: string | undefined, |
13 | message_deduplication_id: string | undefined, |
14 | delay_seconds: number | undefined |
15 | ) { |
16 | if (payload == null || payload === "") { |
17 | throw new Error("payload is required: SQS does not accept an empty message") |
18 | } |
19 | |
20 | |
21 | |
22 | const region = |
23 | new URL(queue_url).hostname |
24 | .split(".") |
25 | .find((label) => /^[a-z]{2}(-[a-z]+)+-\d+$/.test(label)) || |
26 | auth.region || |
27 | "us-east-1" |
28 | const client = new SQSClient({ |
29 | region, |
30 | credentials: { |
31 | accessKeyId: auth.awsAccessKeyId, |
32 | secretAccessKey: auth.awsSecretAccessKey, |
33 | }, |
34 | }) |
35 | |
36 | const attributes = Object.entries(message_attributes ?? {}) |
37 | .filter(([, v]) => v != null && v !== "") |
38 | .map(([k, v]) => [k, typeof v === "string" ? v : JSON.stringify(v)]) |
39 | |
40 | const { $metadata, ...result } = await client |
41 | .send( |
42 | new SendMessageCommand({ |
43 | QueueUrl: queue_url, |
44 | MessageBody: |
45 | typeof payload === "string" ? payload : JSON.stringify(payload), |
46 | MessageAttributes: attributes.length |
47 | ? Object.fromEntries( |
48 | attributes.map(([k, v]) => [ |
49 | k, |
50 | { DataType: "String", StringValue: v }, |
51 | ]) |
52 | ) |
53 | : undefined, |
54 | MessageGroupId: message_group_id || undefined, |
55 | MessageDeduplicationId: message_deduplication_id || undefined, |
56 | |
57 | DelaySeconds: delay_seconds || undefined, |
58 | }) |
59 | ) |
60 | .catch((e) => { |
61 | throw new Error(`${e.name}: ${e.message}`) |
62 | }) |
63 | return result |
64 | } |
65 |
|