MQTT trigger script template

Script windmill Verified

by dieriba.pro916 · 2/28/2025

The script

Submitted by dieriba.pro916 Bun
Verified 369 days ago
1
/**
2
 * General Trigger Preprocessor
3
 * 
4
 * ⚠️ This function runs BEFORE the main function.
5
 * 
6
 * It processes raw trigger data (e.g., MQTT, HTTP, SQS) before passing it to `main()`.
7
 * Common tasks:
8
 * - Convert binary payloads to string/JSON
9
 * - Extract metadata
10
 * - Filter messages
11
 * - Add timestamps/context
12
 * 
13
 * The returned object determines `main()` parameters:
14
 * - `{a: 1, b: 2}` → `main(a, b)`
15
 * - `{payload}` → `main(payload)`
16
 * 
17
 * @param event - Trigger data (e.g., MQTT, HTTP)
18
 * @returns Processed data for `main()`
19
 */
20
export async function preprocessor(
21
  event: {
22
    kind: 'mqtt',
23
    payload: string, // base 64 encoded payload
24
    topic: string,
25
    retain: boolean,
26
    pkid: number,
27
    qos: number,
28
    v5?: {
29
      payload_format_indicator?: number,
30
      topic_alias?: number,
31
      response_topic?: string,
32
      correlation_data?: Array<number>,
33
      user_properties?: Array<[string, string]>,
34
      subscription_identifiers?: Array<number>,
35
      content_type?: string
36
    }
37
  },
38
) {
39
  if (event.kind === 'mqtt') {
40
    const payloadAsString = atob(event.payload);
41

42
    return {
43
      contentType: event.v5?.content_type,
44
      payload: event.payload,
45
      payloadAsString
46
    };
47
  }
48
  // We assume the script is triggered by an MQTT message, which is why an error is thrown for other trigger kinds.
49
  // If the script is intended to support other triggers, update this logic to handle the respective trigger kind.
50
  throw new Error(`Expected mqtt trigger kind got: ${event.kind}`)
51
}
52

53
/**
54
 * Main Function - Handles processed trigger events
55
 * 
56
 * ⚠️ Called AFTER `preprocessor()`, with its return values.
57
 * 
58
 * @param payload - Raw base64 encoded payload
59
 * @param payloadAsString - Decoded string payload
60
 * @param contentType - MQTT v5 content type (if available)
61
 */
62
export async function main(payload: string, payloadAsString: string, contentType?: string) {
63

64
}