NestJS on AWS Lambda

오픈소스·2022년 12월 18일
0
post-thumbnail
post-custom-banner

nestjs 프로젝트 생성

https://docs.nestjs.com/first-steps

$ npm i -g @nestjs/cli
$ nest new serverless-nestjs

nestjs 프로젝트 확인

$ cd serverless-nestjs
$ npm run start

Connect http://localhost:3000/

serverless 프로젝트 생성

https://www.serverless.com/framework/docs/providers/openwhisk/guide/installation

$ cd serverless-nestjs
$ npm install -g serverless
$ mv .gitignore .gitignore_nestjs
$ serverless create --template aws-nodejs
$ mv .gitignore .gitignore_serverlessjs
$ cp .gitignore_nestjs .gitignore
  1. merge .gitignore

  2. replace handler.js --> src/lambda.ts

    • https://github.com/youngkiu/serverless-nestjs/blob/main/src/lambda.ts

      import { configure as serverlessExpress } from '@vendia/serverless-express';
      import { NestFactory } from '@nestjs/core';
      import { AppModule } from './app.module';
      
      let cachedServer;
      
      export const handler = async (event, context) => {
        if (!cachedServer) {
          const nestApp = await NestFactory.create(AppModule);
          await nestApp.init();
          cachedServer = serverlessExpress({ app: nestApp.getHttpAdapter().getInstance() });
        }
      
        return cachedServer(event, context);
      }
  3. update serverless.yml

    • https://github.com/youngkiu/serverless-nestjs/blob/main/serverless.yml
      ...
      functions:
        hello:
          handler: dist/lambda.handler
      #    The following are a few example events you can configure
      #    NOTE: Please make sure to change your handler code to work with those events
      #    Check the event documentation for details
          events:
            - httpApi:
                path: /{any+}
                method: any
      ...
$ npm i -D serverless-jetpack
$ npm i @vendia/serverless-express
$ npm run build
$ serverless deploy

Deploying serverless-nestjs to stage dev (ap-northeast-2)

✔ Service deployed to stack serverless-nestjs-dev (116s)

endpoint: ANY - https://65re6n90z8.execute-api.ap-northeast-2.amazonaws.com/{any+}
functions:
  hello: serverless-nestjs-dev-hello (4.5 MB)

Need a better logging experience than CloudWatch? Try our Dev Mode in console: run "serverless --console"
$ curl  https://65re6n90z8.execute-api.ap-northeast-2.amazonaws.com/                                         Hello World!%   

serverless 프로젝트 제거

$ serverless remove
Removing serverless-nestjs from stage dev (ap-northeast-2)

✔ Service serverless-nestjs has been successfully removed (26s)

Ref)

post-custom-banner

0개의 댓글