[英]NestJs Eventbridge Lambda function
我有一個使用 NestJs 和無服務器框架編寫的系統,每個端點都是 aws 上的 lambda function。 其中一個功能不是端點,而是來自 AWS eventbridge 的觸發器。 由於此 function 不是端點,因此不能包含在 NestJs 模塊中,因為它必須單獨導出。 我的問題是,當事件到達 Eventbridge 並觸發 lambda 時,我必須調用 NestJs 服務,但我無法執行此操作,因為 lambda function 在 NestJs 環境之外。 這是我從模塊外部調用 NestJs 服務的一種方式嗎?
這是無服務器框架配置
functions:
function 1(NestJs controller):
handler: src/lambda.handler
events:
- http:
cors: true
method: post
path: entrypoint for function 1
Function 2 (External from NestJs modules):
handler: path to lambda function
events:
- eventBridge:
eventBus: eventbus name
pattern:
source:
- source
目前我正在使用 axios 調用另一個 NestJs 端點來傳遞接收到的有效負載。 正如您在 lambda function 文件中所見:
import { Context, Handler } from 'aws-lambda'
import axios from 'axios'
export const handler: Handler = async (event: any, context: Context) => {
return await axios
.post(
'lambda function production url',
event.detail
)
.then((data) => {
console.log('data', data)
return data
})
.catch((error) => {
console.log('error', error)
return error
})
}
這是lambda的controller function 1
import { Body, Controller, Post } from '@nestjs/common'
import { MyService } from './enrichment.service'
@Controller('function1')
export class EnrichmentController {
constructor(private readonly myService: MyService) {}
@Post('entrypoint')
sendForm(@Body() body) {
return this.myService.start(body)
}
}
這是服務
import { forwardRef, Inject, Injectable } from '@nestjs/common'
import { EventbridgeService } from '../eventbridge/eventbridge.service'
import { CampaignsService } from '../campaigns/campaigns.service'
import { UploadedDataService } from '../uploaded-data/uploaded-data.service'
@Injectable()
export class MyService {
constructor(
private readonly anotherService: AnotherService,
) {}
async start(body) {
return this.anotherService.updateData(body)
}
}
問題是:這是從 function 文件調用所有 NestJs 結構的方法嗎,因為它在 NestJs 模塊之外,因為這個 function 的觸發器不是 http 請求而是來自 Eventbridge 的觸發器? 太感謝了。
您可以使用“獨立”Nest 應用程序並將事件數據直接傳遞給MyService
您可以使用 NEstJs 獨立應用程序,並使您的處理程序像這樣 export const checkDeletion: Handler = async (event: any, context: Context) => {
async function bootstrap() {
const app = await NestFactory.createApplicationContext(AppModule);
await app
.select(SchedulerModule)
.get(SchedulerService, { strict: true })
.runScheduler();
}
await bootstrap();
};
之后從 serverless.yaml 調用你的處理程序
functions:
followup-emails:
environment:
STAGE: ${opt:stage}
name: followup-emails-${opt:stage}
handler: src/lambda.checkDeletion
events:
- schedule: rate(1 day)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.