# Node - RED Widgets for Message Injection

For injecting messages into your custom queue server, you'll use the HTTP Request node as the primary widget. Here's how to set it up:

## Basic Setup with HTTP Request Node

The simplest approach uses Node - RED's built-in HTTP Request node:

```javascript
// Flow: [Inject/Trigger] -> [Function] -> [HTTP Request] -> [Debug]
```

### Manual Testing - Inject Node

For manual testing and one - off messages:

```javascript
[Inject Node]-> [Function Node] -> [HTTP Request Node]

// Inject node configuration:
// - Set msg.payload to your test data
// - Can set msg.priority as an additional property

// Function node code:
msg.url = "<http://your-queue-server:8080/publish>";
msg.method = "POST";
msg.headers = { "Content-Type": "application/json" };

// Prepare the request body
msg.payload = {
    queue: "my_queue",
    priority: msg.priority || 1000,
    payload: JSON.stringify(msg.payload),
    max_retries: 3
};

return msg;

// HTTP Request node:
// - Method: Set to "msg.method"
// - URL: Set to "msg.url"
// - Return: "a parsed JSON object"
```

### Dashboard Button - For User - Triggered Messages

If you have node - red - dashboard installed:

```javascript
[Dashboard Button]-> [Function] -> [HTTP Request]

// Dashboard button can trigger with user input
// Function node same as above
```

### Automated Triggers

For automated message injection based on events:

```javascript
// Time-based
[Inject(Repeat)] -> [Function] -> [HTTP Request]

    // MQTT triggered
    [MQTT In]-> [Function] -> [HTTP Request]

    // File watcher triggered
    [Watch Node]-> [Read File] -> [Function] -> [HTTP Request]

    // HTTP endpoint triggered (webhook)
    [HTTP In]-> [Function] -> [HTTP Request] -> [HTTP Response]
```

### Creating a Reusable Subflow

For cleaner flows, create a subflow that encapsulates the queue publishing:

```javascript
// Create a subflow with:
// Input -> [Function] -> [HTTP Request] -> Output

// Subflow Function node:
const config = {
    queueServer: env.get("QUEUE_SERVER") || "<http://localhost:8080>",
    defaultQueue: env.get("DEFAULT_QUEUE") || "default",
    defaultPriority: parseInt(env.get("DEFAULT_PRIORITY") || "1000")
};

msg.url = `${config.queueServer}/publish`;
msg.method = "POST";
msg.headers = { "Content-Type": "application/json" };

msg.payload = {
    queue: msg.queue || config.defaultQueue,
    priority: msg.priority || config.defaultPriority,
    payload: typeof msg.payload === 'string'
        ? msg.payload
        : JSON.stringify(msg.payload),
    max_retries: msg.max_retries || 3
};

return msg;

// Then use it like:
[Any Trigger] -> [Queue Publisher Subflow] -> [Debug]
```

### Complete Example Flow

Here's a complete, importable Node-RED flow:

```json
[
  {
    "id": "inject1",
    "type": "inject",
    "name": "Test Message",
    "props": [
      { "p": "payload" },
      { "p": "priority", "v": "100", "vt": "num" },
      { "p": "queue", "v": "orders", "vt": "str" }
    ],
    "payload": "{\"orderId\": 12345, \"amount\": 99.99}",
    "payloadType": "json",
    "repeat": "",
    "wires": [["function1"]]
  },
  {
    "id": "function1",
    "type": "function",
    "name": "Prepare Queue Message",
    "func": "msg.url = \"http://queue-server:8080/publish\";\nmsg.method = \"POST\";\nmsg.headers = {\"Content-Type\": \"application/json\"};\n\nmsg.payload = {\n    queue: msg.queue || \"default\",\n    priority: msg.priority || 1000,\n    payload: JSON.stringify(msg.payload),\n    max_retries: 3\n};\n\nreturn msg;",
    "wires": [["http1"]]
  },
  {
    "id": "http1",
    "type": "http request",
    "name": "Send to Queue",
    "method": "use",
    "ret": "obj",
    "paytoqs": "ignore",
    "url": "",
    "tls": "",
    "persist": false,
    "proxy": "",
    "wires": [["debug1"]]
  },
  {
    "id": "debug1",
    "type": "debug",
    "name": "Queue Response",
    "active": true,
    "wires": []
  }
]
```

### For High - Volume Messages

If you need to inject many messages quickly, consider a batch approach:

```javascript
// Function node for batch publishing
const messages = msg.payload; // Assume array of messages
const requests = messages.map((item) => ({
  url: "<http://queue-server:8080/publish>",
  method: "POST",
  headers: { "Content-Type": "application/json" },
  payload: {
    queue: item.queue || "default",
    priority: item.priority || 1000,
    payload: JSON.stringify(item.data),
    max_retries: 3,
  },
}));

// Send multiple messages
return requests.map((req) => ({ ...req }));

// This will trigger multiple HTTP requests in parallel
```

### Alternative: Custom Node

If you want a cleaner interface, you could create a custom Node - RED node specifically for your queue:

```javascript
// In a file: node-red-contrib-custom-queue/queue-publish.js
module.exports = function (RED) {
  function QueuePublishNode(config) {
    RED.nodes.createNode(this, config);
    const node = this;

    node.on("input", async function (msg) {
      const axios = require("axios");

      try {
        const response = await axios.post(`${config.server}/publish`, {
          queue: msg.queue || config.defaultQueue,
          priority: msg.priority || config.defaultPriority,
          payload: JSON.stringify(msg.payload),
          max_retries: config.maxRetries,
        });

        msg.messageId = response.data.id;
        node.send(msg);
      } catch (error) {
        node.error(error, msg);
      }
    });
  }

  RED.nodes.registerType("queue-publish", QueuePublishNode);
};
```

## Common Patterns

Priority from message type:

```javascript
// In Function node before HTTP Request — numeric priorities
msg.priority =
  msg.topic === "urgent" ? 10 : msg.topic === "normal" ? 100 : 1000;

// Text priorities (for queues with priority_kind: "Text")
msg.priority = msg.topic || "default";
```

Dynamic queue selection:

```javascript
// Route to different queues based on content
msg.queue =
  msg.payload.type === "order"
    ? "orders"
    : msg.payload.type === "notification"
      ? "notifications"
      : "default";
```

The HTTP Request node is your main tool, with Function nodes for message preparation. This gives you full flexibility without requiring any special queue - specific nodes.
