没有使用Serverless和AWS在NestJS上注入依赖项

时间:2019-06-02 14:50:55

标签: serverless-framework nestjs aws-serverless

所有人,

我正在尝试设置我的第一个NestJS应用程序。它由AWS上的Serverless支持。

我创建了一个简单的Controller,它具有一个Service作为依赖项。当我使用HTTP客户端访问端点时,应包含Service实例的对象为undefined。我无法使其工作。你能帮忙吗?

handler.ts

import { Context, Handler } from 'aws-lambda';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './src/module';
import { Server } from 'http';
import { ExpressAdapter } from '@nestjs/platform-express';
import * as serverless from 'aws-serverless-express';
import * as express from 'express';
import {DB} from './src/libs/db';

let cachedServer: Server;

function bootstrapServer(): Promise<Server> {
  const expressApp = express();
  const adapter = new ExpressAdapter(expressApp);
  return NestFactory.create(AppModule, adapter)
    .then(app => app.enableCors())
    .then(app => app.init())
    .then(() => DB.connect())
    .then(() => serverless.createServer(expressApp));
}

export const handle: Handler = (event: any, context: Context) => {
  if (!cachedServer) {
    bootstrapServer().then(server => {
      cachedServer = server;
      return serverless.proxy(server, event, context);
    });
  } else {
    return serverless.proxy(cachedServer, event, context);
  }
};

module.ts

import { Module } from '@nestjs/common';
import { EventController } from './event.controller';
import { EventService } from './event.service';

@Module({
  controllers: [EventController],
  providers: [EventService],
})
export class AppModule {}

event.service.ts

import { Injectable } from '@nestjs/common';

interface Event{}

@Injectable()
export class EventService {
  create(event: Event) {
    return {
      id: Date.now()
    }
  }
}

event.controller.ts

import { Controller, Post, Body } from '@nestjs/common';
import { EventService } from './event.service';

interface Event { }

@Controller('event')
export class EventController {
  constructor(private readonly eventService: EventService) { }

  @Post()
  async create(@Body() req)

{
    this.eventService.create(req);
  }
}

因此this.eventService始终是undefined。此实现有什么问题?

1 个答案:

答案 0 :(得分:0)

也许您缺少tsconfig中的一行,请在下面添加:

“ emitDecoratorMetadata”:是

Nestjs的上帝致敬卡米尔先生的回信: https://stackoverflow.com/a/50121886/6301493