Как получить экземпляр Express, созданный в main.ts в другом модуле в nestjs - PullRequest
0 голосов
/ 13 марта 2019

Я пытаюсь использовать анализатор busboybody для анализа данных многочастной формы. Это промежуточное программное обеспечение может поддерживаться путем определения промежуточного программного обеспечения внутри экспресс-экземпляра. Теперь я не хочу заявлять об этом в main.ts, а скорее в конкретном модуле, где я собираюсь использовать файлы (давайте назовем это fileModule). Итак, моя задача - создать fileMiddleware и объявить в нем этот анализатор промежуточного программного обеспечения. Для этого мне нужно получить экземпляр express в fileMiddleware. Может ли кто-нибудь помочь мне в этом?

Вот мой пример main.ts

import { logger } from './shared/utils/logger';

import { NestFactory, FastifyAdapter } from '@nestjs/core';
import * as express from 'express';
import { AppModule } from './app.module';
import { EnvConfig } from './shared/utils/config';
import dotenv = require('dotenv');
import { isNullOrUndefined } from 'util';
import { AppService } from './app.service';
import { ConfigProviderService } from './config-module/providers/config-provider/config-provider.service';
import {DocumentBuilder, SwaggerModule} from '@nestjs/swagger';

declare const module: any;

// bootstraps the app -  this is the entry point of the app
// so we say which module has to be loaded initally - AppModule in this case
// it uses async await model which makes the app wait fr the event to be completed before the
// next event occurs. so even if it follows asynchronous coding, there is a block happens
// when we call await on a statement/expression
async function bootstrap() {
// the fastify adapter is a seperate webframework which speeds up the req processing
// capabality to 30000 requests per second

// this is equilent to create the server using fastify rather than just express or hapi

 // const app = await NestFactory.create(AppModule, new FastifyAdapter());
 // incase 
 let app;
 const instance = express();


 const hostDomain = AppModule.isDev ? `${AppModule.host}:${AppModule.port}` : AppModule.host;
 if ( process.env.LCP === 'development' || isNullOrUndefined(process.env.LCP)) {

    // this makes sure that all the default logger logs to the console
      app = await NestFactory.create(AppModule, instance, {
         logger: console,
     });
 } else {
      app = await NestFactory.create(AppModule, instance);
 }






 // this is to enable HMR
 if (module.hot) {
        // tslint:disable-next-line:no-console
        console.log('module', module);
        module.hot.accept();
        module.hot.dispose(() => app.close());
    }

 const swaggerScheme = 'http';

 const swaggerOptions = new DocumentBuilder().setBasePath(AppModule.contextPath)
 .setDescription('nestJs description').setHost(hostDomain).setContactEmail('XXXX')
 .addTag('TestModule')
 .addTag('FirstModule')
 .addTag('NewModule')
 .addBearerAuth('asasasas')
 .setTitle('Nest JS - Buidling a sample server').setSchemes(swaggerScheme).build();

 const swaggerDoc = SwaggerModule.createDocument(app, swaggerOptions);

 app.setGlobalPrefix(AppModule.contextPath);

 // now we need to expose the swagger.json to be consumed
 // just like express use the router middleware here
 app.use('/api/rootModule', (req, res)=> {
     res.send(swaggerDoc);
 });

 // now to use swagger -ui
 // the docs patht and the swagger url should be the same
 SwaggerModule.setup('/api/swagger/docs', app, null, {
    swaggerUrl: '/api/rootModule',
    explorer: true,
    swaggerOptions: {
        docExpansion: true,
        fiter: true,
        showRequestDuration: true,
    }
 });
 await app.listen(AppModule.port) ;
}
bootstrap();

Это промежуточное ПО, где мне нравится использовать busboybodyparser

import { Injectable, MiddlewareFunction, NestMiddleware } from '@nestjs/common';
import * as busboyBodyParser from 'busboy-body-parser';

@Injectable()
export class FileStorageMiddlewareMiddleware implements NestMiddleware {
  resolve(...args: any[]): MiddlewareFunction {
    return (req, res, next) => {
      // this is the part that requires the express instance but currently 
      // it is code with the req instance which I presume is incorrect?
      //req.busboyBodyParser([{limit: '20mb'}, {multi: true}]);
      next();
    };
  }
}
...