0

This is my configuration, the nestjs application starts but I have not been able to execute the controllers.

import { app, HttpRequest, HttpResponseInit } from '@azure/functions';
import { INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from '../app.module';

let appNest: INestApplication;

async function createAppNest() {
  if (!appNest) {
    appNest = await NestFactory.create(AppModule);
    await appNest.init();
  }
}

export async function httpTrigger(
  request: HttpRequest,
  context: any
): Promise<HttpResponseInit> {
  context.log('EJECUCIÓN FUNCIÓN');
  await createAppNest();

  const expressApp = appNest.getHttpAdapter().getInstance();
  const response = expressApp(request, context.res);

  return {
    status: 200,
    body: response,
  };
}

app.http('afiliacion', {
  methods: ['GET', 'POST'],
  authLevel: 'anonymous',
  handler: httpTrigger,
  route: '{*segments}',
});

Versions:

@azure/functions: 4.6.0
nestjs: 10.4.8
nodejs: 22.11.0

Error:

\[Nest\] 20948  - 29/11/2024, 9:26:48 a. m.   ERROR \[AllExceptionsFilter\] Unexpected Error
\[2024-11-29T14:26:48.953Z\] \[error\] Worker uncaught exception (learn more: https://go.microsoft.com/fwlink/?linkid=2097909 ): TypeError: Cannot read properties of undefined (reading 'status')     at AllExceptionsFilter.catch (C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\dist\\filters\\http-exception.filter.js:54:29)     at ExceptionsHandler.invokeCustomFilters (C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\node_modules@nestjs\\core\\exceptions\\exceptions-handler.js:30:26)     at ExceptionsHandler.next (C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\node_modules@nestjs\\core\\exceptions\\exceptions-handler.js:14:18)     at C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\node_modules@nestjs\\core\\router\\router-proxy.js:25:35     at Layer.handle_error (C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\node_modules\\express\\lib\\router\\layer.js:71:5)     at trim_prefix (C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\node_modules\\express\\lib\\router\\index.js:326:13)     at C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\node_modules\\express\\lib\\router\\index.js:286:9     at Function.process_params (C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\node_modules\\express\\lib\\router\\index.js:346:12)     at next (C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\node_modules\\express\\lib\\router\\index.js:280:10)     at Layer.handle_error (C:\\Users\\amartinez\\Downloads\\Proyectos\\servicio\\node_modules\\express\\lib\\router\\layer.js:67:12)
\[2024-11-29T14:26:49.025Z\] Language Worker Process exited. Pid=20948.

How to properly integrate Nestjs and Azure Function?

1 Answer 1

0

I think you need to adjust the NestJS application initialization.

NestJS needs to run on an Express server for compatibility with Azure Functions. Make sure that your Express server adapter is properly integrated. You should use the express package to achieve this.

import { app, HttpRequest, HttpResponseInit } from '@azure/functions';
import { INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from '../app.module';
import * as express from 'express';

let appNest: INestApplication;
const expressApp = express();

async function createAppNest() {
  if (!appNest) {
    const adapter = new ExpressAdapter(expressApp);
    appNest = await NestFactory.create(AppModule, adapter);
    await appNest.init();
   }
 }

export async function httpTrigger(
  request: HttpRequest,
  context: any
): Promise<HttpResponseInit> {
  context.log('Executing HTTP Trigger');

  await createAppNest();

  // Map Azure Function request to Express request/response
  const response = new Promise<HttpResponseInit>((resolve, reject) => {
     const res = {
       status: (statusCode: number) => ({
         send: (body: any) => resolve({ status: statusCode, body }),
      }),
      send: (body: any) => resolve({ status: 200, body }),
  };
  expressApp(request, res as any, (err: any) => {
     if (err) reject(err);
  });
});

return response;
}

// Register the Azure Function trigger
app.http('afiliacion', {
 methods: ['GET', 'POST'],
 authLevel: 'anonymous',
 handler: httpTrigger,
 route: '{*segments}', // Match all routes
});

Now you are using Express adapter. Make sure Azure functions HTTP requests are mapped to Express requests and the responses are properly returned.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.