Azure / azure-functions-nodejs-library

The Node.js framework for Azure Functions
https://www.npmjs.com/package/@azure/functions
MIT License
58 stars 14 forks source link

[Azure functions v4.0]: How to get the input from service bus trigger? #91

Closed ilyas-shah closed 1 year ago

ilyas-shah commented 1 year ago
import {
  HttpRequest,
  HttpResponseInit,
  InvocationContext,
  app,
  input,
  output,
} from "@azure/functions";

const outputSignalR = output.generic({
  type: "signalR",
  connection: "AzureSignalRConnectionString",
  hubName: "serverless",
});

async function handleRequest(
  request: HttpRequest,
  context: InvocationContext
): Promise<void> {
  console.log(request, context.extraOutputs)
  context.extraOutputs.set(outputSignalR, {
    target: "newMessage",
    arguments: [
      {
        message: request.body,
        timestamp: Date.now(),
      },
    ],
  });
}

app.serviceBusQueue("serviceBusTrigger", {
  connection: "AzureWebJobsServiceBus",
  extraOutputs: [outputSignalR],
  queueName: "testqueue",
  handler: handleRequest,
});

In this code, I have setup a trigger for a service bus. Once I get the message from the service bus, I want to send it to the signalR service (clients are connected to it).

When logging request and content, I can't seem to find the message from the service bus.

Extra info Programming model: v4 [typescript] Development: local Connections: actuall connection string used for Azure service bus, storage account, and signalR.

ilyas-shah commented 1 year ago

@ejizba Please help.

ilyas-shah commented 1 year ago

Turns out I was not properly handing sending messages to the service bus. I was missing using await request.text() in my POST request handler that sends message to queue.

async function handleRequest(
  request: HttpRequest,
  context: InvocationContext
): Promise<HttpResponseInit> {
  if (request.method === "GET") {
    return renderHomePage(request, context);
  } else if (request.method === "POST") {
    context.log(request.body)
    const message = await request.text();
    return sendMessageToQueue(message, context);
  }
  return Promise.resolve({ body: "Request method not supported" });
}

Also, modified the above code for better readability:

import { InvocationContext, app, output } from "@azure/functions";

const outputSignalR = output.generic({
  type: "signalR",
  connection: "AzureSignalRConnectionString",
  hubName: "serverless",
});

async function serviceBusHandler(
  message: unknown,
  context: InvocationContext
): Promise<void> {
  context.extraOutputs.set(outputSignalR, {
    target: "newMessage",
    arguments: [
      {
        message,
        timestamp: Date.now(),
      },
    ],
  });
}

app.serviceBusQueue("serviceBusTrigger", {
  connection: "AzureWebJobsServiceBus",
  extraOutputs: [outputSignalR],
  queueName: "testqueue",
  handler: serviceBusHandler,
});