/**
* General Trigger Preprocessor Function
*
* ⚠️ IMPORTANT: This preprocessor function is ALWAYS called FIRST, before the main function.
*
* This example assumes the script was triggered by an MQTT event, but the same
* preprocessor can handle other trigger types by checking wm_trigger.kind.
*
* Flow:
* 1. Trigger event occurs (MQTT message in this example)
* 2. Preprocessor function is called FIRST
* 3. Main function is called with the return values from preprocessor
*
* You can transform the raw trigger data here before it reaches your main function.
* Common transformations include:
* - Converting binary payload to string or JSON
* - Extracting metadata from the trigger source
* - Filtering messages
* - Adding timestamps or other context
*
* IMPORTANT: The object you return from this preprocessor determines the parameters passed to your main function:
* - If you return {a: 1, b: 2}, then main will be called as main(a, b)
* - If you return {payload}, then main will be called as main(payload)
*
* @param wm_trigger - Information about the trigger source (could be MQTT, HTTP, email, etc.)
* @param payload - The raw data from the trigger (type depends on the trigger kind)
* @returns An object with the arguments to pass to the main function
*/
export async function preprocessor(
wm_trigger: {
kind: 'http' | 'email' | 'webhook' | 'websocket' | 'kafka' | 'nats' | 'postgres' | 'sqs' | 'mqtt',
mqtt?: {
topic: string,
retain: boolean,
pkid: number,
qos: number,
v5?: {
payload_format_indicator?: number,
topic_alias?: number,
response_topic?: string,
correlation_data?: Array<number>,
user_properties?: Array<[string, string]>,
subscription_identifiers?: Array<number>,
content_type?: string
}
}
},
/**
* Each trigger type has its own specific parameters:
* - For MQTT: 'payload' (Uint8Array of raw message bytes)
* - For SQS: 'msg' (message data)
* - Other trigger types have their own specific properties
*/
payload: Uint8Array,
) {
if (wm_trigger.kind === 'mqtt' && wm_trigger.mqtt) {
// Convert the binary payload to a string
// This assumes the binary data represents a string (e.g., UTF-8 encoded text)
const payloadAsString = new TextDecoder().decode(payload);
return {
contentType: wm_trigger.mqtt.v5?.content_type,
payload,
payloadAsString
}
}
else {
return {
kind: wm_trigger.kind
}
}
}
/**
* Main Function - Handles Trigger Events
*
* ⚠️ This function is called AFTER the preprocessor function.
*
* This example assumes we're handling an MQTT trigger event where the payload is a string.
* The main function receives arguments based on what the preprocessor returned.
*
* @param contentType - For MQTT: The content type from MQTT v5 properties if available
* @param payload - The raw binary payload from MQTT
* @param payloadAsString - The payload as a string (decoded from binary data)
*/
export async function main(payload: string, contentType?: string, payloadAsString: string) {
}Submitted by dieriba.pro916 441 days ago