bun-aws-lambda
1
总安装量
1
周安装量
#55329
全站排名
安装命令
npx skills add https://github.com/gilbertopsantosjr/fullstacknextjs --skill bun-aws-lambda
Agent 安装分布
cursor
1
claude-code
1
Skill 文档
Bun AWS Lambda Expert
Expert guidance for AWS Lambda functions using Bun runtime. Covers handler creation, deployment patterns, and Node.js migration.
Handler Template
import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda'
export async function handler(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
try {
const { pathParameters, body, queryStringParameters } = event
const payload = body ? JSON.parse(body) : undefined
// Business logic here
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ success: true }),
}
} catch (error) {
console.error('Handler error:', error)
return {
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ error: 'Internal server error' }),
}
}
}
Event Source Decision
Which event source?
âââ HTTP API (API Gateway v2) â APIGatewayProxyEventV2
âââ REST API (API Gateway v1) â APIGatewayProxyEvent
âââ ALB â ALBEvent
âââ SQS â SQSEvent (with SQSBatchResponse for partial failures)
âââ SNS â SNSEvent
âââ EventBridge â EventBridgeEvent<DetailType>
âââ S3 â S3Event
âââ DynamoDB Streams â DynamoDBStreamEvent
âââ Scheduled (Cron) â ScheduledEvent
Deployment Decision
How to deploy Bun Lambda?
âââ Container Image (Recommended)
â âââ Simplest setup
â âââ Full control over runtime
â âââ Cold start: ~300-500ms
âââ Custom Runtime Layer
â âââ Smaller package size
â âââ Faster cold starts (~100-200ms)
â âââ More complex setup
âââ Node.js Runtime + Bun Build
âââ Simplest if code is Node-compatible
âââ Use Bun only as bundler
Container Image Quick Start
Dockerfile
FROM oven/bun:1 AS builder
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile --production
COPY src/ ./src/
RUN bun build src/handler.ts --outdir=dist --target=bun --minify
FROM public.ecr.aws/lambda/provided:al2023
RUN curl -fsSL https://bun.sh/install | bash
ENV PATH="/root/.bun/bin:${PATH}"
WORKDIR ${LAMBDA_TASK_ROOT}
COPY /app/dist/ ./
COPY bootstrap ${LAMBDA_RUNTIME_DIR}/bootstrap
RUN chmod +x ${LAMBDA_RUNTIME_DIR}/bootstrap
CMD ["handler.handler"]
Bootstrap (TypeScript)
// bootstrap.ts
const RUNTIME_API = `http://${Bun.env.AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime`
const [moduleName, functionName] = (Bun.env._HANDLER ?? 'handler.handler').split('.')
const handlerModule = await import(`./${moduleName}.js`)
const handler = handlerModule[functionName]
while (true) {
const next = await fetch(`${RUNTIME_API}/invocation/next`)
const requestId = next.headers.get('Lambda-Runtime-Aws-Request-Id')!
const event = await next.json()
try {
const result = await handler(event, { awsRequestId: requestId })
await fetch(`${RUNTIME_API}/invocation/${requestId}/response`, {
method: 'POST',
body: JSON.stringify(result),
})
} catch (error) {
await fetch(`${RUNTIME_API}/invocation/${requestId}/error`, {
method: 'POST',
body: JSON.stringify({ errorMessage: String(error) }),
})
}
}
Bun-Specific Patterns
Environment Variables
const config = {
dbUrl: Bun.env.DATABASE_URL!,
apiKey: Bun.env.API_KEY!,
stage: Bun.env.STAGE ?? 'dev',
}
File Operations
// Read JSON config
const config = await Bun.file('config.json').json()
// Write to /tmp
await Bun.write('/tmp/output.json', JSON.stringify(data))
Native Fetch
const response = await fetch('https://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
const data = await response.json()
Hashing
const hash = Bun.hash(content, 'sha256').toString(16)
Cold Start Optimization
- Bundle with Bun: Single file, tree-shaken
- Lazy initialization: Load heavy deps on first request
- Use AWS SDK v3: Modular imports
- Minimize dependencies: Native fetch, no axios
- Consider provisioned concurrency: For latency-critical
// Lazy initialization pattern
let db: DatabaseClient | null = null
async function getDb() {
if (!db) {
const { DatabaseClient } = await import('./db')
db = new DatabaseClient(Bun.env.DATABASE_URL!)
}
return db
}
Best Practices
- Types: Always use
aws-lambdatypes for event/response - Error Handling: Catch all errors, return proper HTTP status
- Logging: Use
console.errorfor errors (CloudWatch compatible) - Validation: Validate input early, fail fast
- Idempotency: Design for retries on async event sources
- Timeouts: Set appropriate Lambda timeout for use case
References
Detailed patterns and examples:
- event-sources.md: Event structures for API Gateway, SQS, SNS, EventBridge, S3, DynamoDB Streams
- deployment-patterns.md: Container images, custom runtime layers, IaC templates (CDK, SAM, Terraform, SST)
- nodejs-migration.md: Converting Node.js handlers to Bun, API compatibility
Skill Interface
When using this skill, provide:
{
"lambdaDescription": "What the function does, inputs, outputs, event source",
"bunConstraints": "Bun version, ESM/CJS, HTTP framework preferences",
"deploymentContext": "Container image, Lambda layer, API Gateway, SQS trigger, etc.",
"existingCode": "(optional) Node.js code to convert",
"nonFunctionalRequirements": "(optional) Latency, cold start, observability needs"
}
Response includes:
- handlerCode: Complete Bun Lambda handler code
- runtimeNotes: Bun-specific considerations and choices
- deploymentHints: IaC integration advice
- nextSteps: Testing, hardening, observability suggestions