itsthatguy / avatars-api-middleware

The express middleware for our avatars service
http://avatars.adorable.io
Other
749 stars 96 forks source link

NestJS: requires a middleware function but got a undefined #109

Closed gianlazz closed 3 years ago

gianlazz commented 3 years ago

I'm trying to use this dependency with the NestJS framework and am running into an issue. Below is an example of how I'm using it and beneath that is the error it's throwing.

import avatarsMiddleware from 'adorable-avatars';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use('myAvatars', avatarsMiddleware);
  await app.listen(process.env.PORT || 8080);
}
bootstrap();
TypeError: Router.use() requires a middleware function but got a undefined
    at Function.use (/Users/gianlazzarini/Documents/Development/Lazztech.Hub-Service/node_modules/express/lib/router/index.js:458:13)
    at Function.<anonymous> (/Users/gianlazzarini/Documents/Development/Lazztech.Hub-Service/node_modules/express/lib/application.js:22

Any thoughts?

rylnd commented 3 years ago

Hi @gianlazz ! Apologies in advance as I'm not very familiar with NestJS.

While I wasn't able to find any official examples of using an express middleware in NestJs in their documentation it appears as though they're expecting an object with a use method, rather than the anonymous function that defines our middleware (and your error does seem to point to that expectation).

I also found this post that seems to indicate that the avatars middleware might not currently be compatible (we do not currently export individual handler functions, just the full router instance). If such a refactoring is necessary, that would be a great contribution! 😉

I hope that sets you on the right path; let me know if I can help further!

gianlazz commented 3 years ago

Thank you @rylnd for looking into this. I'll look into it further and may end up making that contribution.

wallopthecat commented 3 years ago

try something like this in your controller

  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(avatarsMiddleware)
      .forRoutes('/avatars');
  }
gianlazz commented 3 years ago

I was able to resolve the issue with the following:

import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import express = require('express');

async function bootstrap() {
  const instance = express();
  instance.use('/avatars', require('adorable-avatars/dist/index'));
  const app = await NestFactory.create(AppModule, new ExpressAdapter(instance));
  await app.listen(process.env.PORT || 8080);
}
bootstrap();