aws-lambda-typescript-integration by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill aws-lambda-typescript-integration使用 TypeScript 创建高性能 AWS Lambda 函数的模式,并优化冷启动。
此技能提供了 AWS Lambda TypeScript 开发的完整模式,涵盖两种主要方法:
两种方法都支持 API Gateway 和 ALB 集成,并具备生产就绪的配置。
在以下情况下使用此技能:
| 方法 | 冷启动 | 捆绑包大小 | 最佳适用场景 | 复杂度 |
|---|---|---|---|---|
| NestJS | < 500ms | 较大 (100KB+) | 复杂 API、企业应用、需要依赖注入 | 中等 |
| 原生 TypeScript | < 100ms |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| 较小 (< 50KB) |
| 简单的处理器、微服务、依赖最少 |
| 低 |
my-nestjs-lambda/
├── src/
│ ├── app.module.ts
│ ├── main.ts
│ ├── lambda.ts # Lambda 入口点
│ └── modules/
│ └── api/
├── package.json
├── tsconfig.json
└── serverless.yml
my-ts-lambda/
├── src/
│ ├── handlers/
│ │ └── api.handler.ts
│ ├── services/
│ └── utils/
├── dist/ # 编译输出
├── package.json
├── tsconfig.json
└── template.yaml
请参阅参考部分获取详细的实现指南。快速示例如下:
NestJS 处理器:
// lambda.ts
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import serverlessExpress from '@codegenie/serverless-express';
import { Context, Handler } from 'aws-lambda';
import express from 'express';
import { AppModule } from './src/app.module';
let cachedServer: Handler;
async function bootstrap(): Promise<Handler> {
const expressApp = express();
const adapter = new ExpressAdapter(expressApp);
const nestApp = await NestFactory.create(AppModule, adapter);
await nestApp.init();
return serverlessExpress({ app: expressApp });
}
export const handler: Handler = async (event: any, context: Context) => {
if (!cachedServer) {
cachedServer = await bootstrap();
}
return cachedServer(event, context);
};
原生 TypeScript 处理器:
// src/handlers/api.handler.ts
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
export const handler = async (
event: APIGatewayProxyEvent,
context: Context
): Promise<APIGatewayProxyResult> => {
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'Hello from TypeScript Lambda!' })
};
};
TypeScript 冷启动取决于捆绑包大小和初始化代码。关键策略:
详见 原生 TypeScript Lambda 获取详细模式。
在模块级别创建客户端并复用:
// 良好实践:初始化一次,在多次调用中复用
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
const dynamoClient = new DynamoDBClient({ region: process.env.AWS_REGION });
export const handler = async (event: APIGatewayProxyEvent) => {
// 使用 dynamoClient - 它已经初始化好了
};
// src/config/env.config.ts
export const env = {
region: process.env.AWS_REGION || 'us-east-1',
tableName: process.env.TABLE_NAME || '',
debug: process.env.DEBUG === 'true',
};
// 验证必需的变量
if (!env.tableName) {
throw new Error('TABLE_NAME environment variable is required');
}
保持 package.json 最小化:
{
"dependencies": {
"aws-lambda": "^3.1.0",
"@aws-sdk/client-dynamodb": "^3.450.0"
},
"devDependencies": {
"typescript": "^5.3.0",
"esbuild": "^0.19.0"
}
}
返回带有结构化错误的正确 HTTP 状态码:
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
try {
const result = await processEvent(event);
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(result)
};
} catch (error) {
console.error('Error processing request:', error);
return {
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ error: 'Internal server error' })
};
}
};
为 CloudWatch Insights 使用结构化日志:
const log = (level: string, message: string, meta?: object) => {
console.log(JSON.stringify({
level,
message,
timestamp: new Date().toISOString(),
...meta
}));
};
log('info', 'Request processed', { requestId: context.awsRequestId });
Serverless 框架:
service: my-typescript-api
provider:
name: aws
runtime: nodejs20.x
functions:
api:
handler: dist/handler.handler
events:
- http:
path: /{proxy+}
method: ANY
AWS SAM:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ApiFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: dist/
Handler: handler.handler
Runtime: nodejs20.x
Events:
ApiEvent:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
有关包含 CI/CD 的完整部署配置,请参阅 Serverless 部署。
@types/aws-lambda 以获得正确的事件类型context.getRemainingTimeInMillis()有关特定主题的详细指导:
输入:
Create a TypeScript Lambda REST API using NestJS for a todo application
过程:
nest new 初始化 NestJS 项目@codegenie/serverless-express, aws-lambdalambda.ts 入口点serverless.yml输出:
输入:
Create a minimal TypeScript Lambda function with optimal cold start
过程:
输出:
输入:
Configure CI/CD for TypeScript Lambda with SAM
过程:
输出:
.github/workflows/deploy.yml版本:1.0.0
每周安装数
202
代码仓库
GitHub 星标数
173
首次出现
2026年2月20日
安全审计
已安装于
codex181
gemini-cli178
github-copilot175
opencode173
cursor173
kimi-cli172
Patterns for creating high-performance AWS Lambda functions in TypeScript with optimized cold starts.
This skill provides complete patterns for AWS Lambda TypeScript development, covering two main approaches:
Both approaches support API Gateway and ALB integration with production-ready configurations.
Use this skill when:
| Approach | Cold Start | Bundle Size | Best For | Complexity |
|---|---|---|---|---|
| NestJS | < 500ms | Larger (100KB+) | Complex APIs, enterprise apps, DI needed | Medium |
| Raw TypeScript | < 100ms | Smaller (< 50KB) | Simple handlers, microservices, minimal deps | Low |
my-nestjs-lambda/
├── src/
│ ├── app.module.ts
│ ├── main.ts
│ ├── lambda.ts # Lambda entry point
│ └── modules/
│ └── api/
├── package.json
├── tsconfig.json
└── serverless.yml
my-ts-lambda/
├── src/
│ ├── handlers/
│ │ └── api.handler.ts
│ ├── services/
│ └── utils/
├── dist/ # Compiled output
├── package.json
├── tsconfig.json
└── template.yaml
See the References section for detailed implementation guides. Quick examples:
NestJS Handler:
// lambda.ts
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import serverlessExpress from '@codegenie/serverless-express';
import { Context, Handler } from 'aws-lambda';
import express from 'express';
import { AppModule } from './src/app.module';
let cachedServer: Handler;
async function bootstrap(): Promise<Handler> {
const expressApp = express();
const adapter = new ExpressAdapter(expressApp);
const nestApp = await NestFactory.create(AppModule, adapter);
await nestApp.init();
return serverlessExpress({ app: expressApp });
}
export const handler: Handler = async (event: any, context: Context) => {
if (!cachedServer) {
cachedServer = await bootstrap();
}
return cachedServer(event, context);
};
Raw TypeScript Handler:
// src/handlers/api.handler.ts
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
export const handler = async (
event: APIGatewayProxyEvent,
context: Context
): Promise<APIGatewayProxyResult> => {
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'Hello from TypeScript Lambda!' })
};
};
TypeScript cold start depends on bundle size and initialization code. Key strategies:
See Raw TypeScript Lambda for detailed patterns.
Create clients at module level and reuse:
// GOOD: Initialize once, reuse across invocations
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
const dynamoClient = new DynamoDBClient({ region: process.env.AWS_REGION });
export const handler = async (event: APIGatewayProxyEvent) => {
// Use dynamoClient - already initialized
};
// src/config/env.config.ts
export const env = {
region: process.env.AWS_REGION || 'us-east-1',
tableName: process.env.TABLE_NAME || '',
debug: process.env.DEBUG === 'true',
};
// Validate required variables
if (!env.tableName) {
throw new Error('TABLE_NAME environment variable is required');
}
Keep package.json minimal:
{
"dependencies": {
"aws-lambda": "^3.1.0",
"@aws-sdk/client-dynamodb": "^3.450.0"
},
"devDependencies": {
"typescript": "^5.3.0",
"esbuild": "^0.19.0"
}
}
Return proper HTTP codes with structured errors:
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
try {
const result = await processEvent(event);
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(result)
};
} catch (error) {
console.error('Error processing request:', error);
return {
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ error: 'Internal server error' })
};
}
};
Use structured logging for CloudWatch Insights:
const log = (level: string, message: string, meta?: object) => {
console.log(JSON.stringify({
level,
message,
timestamp: new Date().toISOString(),
...meta
}));
};
log('info', 'Request processed', { requestId: context.awsRequestId });
Serverless Framework:
service: my-typescript-api
provider:
name: aws
runtime: nodejs20.x
functions:
api:
handler: dist/handler.handler
events:
- http:
path: /{proxy+}
method: ANY
AWS SAM:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ApiFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: dist/
Handler: handler.handler
Runtime: nodejs20.x
Events:
ApiEvent:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
For complete deployment configurations including CI/CD, see Serverless Deployment.
@types/aws-lambda for proper event typingcontext.getRemainingTimeInMillis() for long operationsFor detailed guidance on specific topics:
Input:
Create a TypeScript Lambda REST API using NestJS for a todo application
Process:
nest new@codegenie/serverless-express, aws-lambdalambda.ts entry point with Express adapterserverless.yml with API Gateway eventsOutput:
Input:
Create a minimal TypeScript Lambda function with optimal cold start
Process:
Output:
Input:
Configure CI/CD for TypeScript Lambda with SAM
Process:
Output:
.github/workflows/deploy.ymlVersion: 1.0.0
Weekly Installs
202
Repository
GitHub Stars
173
First Seen
Feb 20, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex181
gemini-cli178
github-copilot175
opencode173
cursor173
kimi-cli172
Supabase Postgres 最佳实践指南 - 8大类别性能优化规则与SQL示例
68,400 周安装