Claude Code के साथ AWS Lambda Optimization
Claude Code का उपयोग करके AWS Lambda optimization के बारे में जानें। Practical tips और code examples शामिल हैं।
Claude Code से AWS Lambda Development को Accelerate करें
AWS Lambda event-driven serverless computing service है। API Gateway, S3, DynamoDB जैसी AWS services के साथ closely integrate होकर scalable backend बनाया जा सकता है। Claude Code का उपयोग करके, Lambda-specific implementation patterns और IaC की coding भी efficiently की जा सकती है।
Lambda Function की Basic Design
> TypeScript में Lambda function बनाओ।
> API Gateway से request process करने वाली configuration में।
// src/handlers/api.ts
import {
APIGatewayProxyEvent,
APIGatewayProxyResult,
Context,
} from 'aws-lambda';
export const handler = async (
event: APIGatewayProxyEvent,
context: Context
): Promise<APIGatewayProxyResult> => {
const { httpMethod, path, body, queryStringParameters } = event;
try {
switch (`${httpMethod} ${path}`) {
case 'GET /users':
return await getUsers(queryStringParameters);
case 'POST /users':
return await createUser(JSON.parse(body || '{}'));
case 'GET /users/{id}':
const id = event.pathParameters?.id;
return await getUser(id!);
default:
return response(404, { error: 'Not Found' });
}
} catch (error) {
console.error('Lambda error:', error);
return response(500, { error: 'Internal Server Error' });
}
};
function response(statusCode: number, body: object): APIGatewayProxyResult {
return {
statusCode,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(body),
};
}
async function getUsers(params: any) {
// DynamoDB से user list fetch करें
return response(200, { users: [] });
}
async function createUser(data: any) {
return response(201, { id: 'new-user-id', ...data });
}
async function getUser(id: string) {
return response(200, { id, name: 'User' });
}
DynamoDB Integration
> DynamoDB का उपयोग करके CRUD operations का utility बनाओ।
// src/lib/dynamodb.ts
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import {
DynamoDBDocumentClient,
GetCommand,
PutCommand,
QueryCommand,
DeleteCommand,
} from '@aws-sdk/lib-dynamodb';
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
const TABLE_NAME = process.env.TABLE_NAME!;
export async function getItem<T>(pk: string, sk: string): Promise<T | null> {
const { Item } = await docClient.send(
new GetCommand({
TableName: TABLE_NAME,
Key: { PK: pk, SK: sk },
})
);
return (Item as T) || null;
}
export async function putItem(item: Record<string, any>): Promise<void> {
await docClient.send(
new PutCommand({
TableName: TABLE_NAME,
Item: {
...item,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
})
);
}
export async function queryItems<T>(
pk: string,
skPrefix?: string
): Promise<T[]> {
const params: any = {
TableName: TABLE_NAME,
KeyConditionExpression: skPrefix
? 'PK = :pk AND begins_with(SK, :sk)'
: 'PK = :pk',
ExpressionAttributeValues: { ':pk': pk },
};
if (skPrefix) {
params.ExpressionAttributeValues[':sk'] = skPrefix;
}
const { Items } = await docClient.send(new QueryCommand(params));
return (Items as T[]) || [];
}
AWS CDK से Infrastructure Definition
> CDK से Lambda + API Gateway + DynamoDB का
> stack define करो।
// lib/api-stack.ts
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Construct } from 'constructs';
export class ApiStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// DynamoDB table
const table = new dynamodb.Table(this, 'MainTable', {
partitionKey: { name: 'PK', type: dynamodb.AttributeType.STRING },
sortKey: { name: 'SK', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
// Lambda function
const apiHandler = new NodejsFunction(this, 'ApiHandler', {
entry: 'src/handlers/api.ts',
handler: 'handler',
runtime: lambda.Runtime.NODEJS_20_X,
architecture: lambda.Architecture.ARM_64,
memorySize: 256,
timeout: cdk.Duration.seconds(30),
environment: {
TABLE_NAME: table.tableName,
NODE_OPTIONS: '--enable-source-maps',
},
bundling: {
minify: true,
sourceMap: true,
},
});
table.grantReadWriteData(apiHandler);
// API Gateway
const api = new apigateway.RestApi(this, 'Api', {
restApiName: 'My API',
deployOptions: { stageName: 'v1' },
});
const users = api.root.addResource('users');
users.addMethod('GET', new apigateway.LambdaIntegration(apiHandler));
users.addMethod('POST', new apigateway.LambdaIntegration(apiHandler));
}
}
Local Development और Testing
# SAM से local execution
sam local start-api
# Specific function test
sam local invoke ApiHandler -e events/get-users.json
# CDK deploy
cdk deploy --require-approval never
Summary
AWS Lambda और Claude Code को combine करके, serverless architecture की design से IaC coding तक efficiently आगे बढ़ सकते हैं। AWS Deployment Guide और Serverless Functions Guide भी reference करें।
AWS Lambda की details के लिए AWS Lambda Official Documentation देखें।
Related Posts
Claude Code से अपने Side Projects को Supercharge कैसे करें [Examples के साथ]
Claude Code से personal development projects को dramatically speed up करना सीखें। Real-world examples और idea से deployment तक practical workflow शामिल है।
Claude Code से Refactoring कैसे Automate करें
Claude Code से efficiently code refactoring automate करना सीखें। Real-world projects के लिए practical prompts और concrete refactoring patterns शामिल हैं।
Claude Code के साथ Complete CORS Configuration Guide
Claude Code का उपयोग करके complete CORS configuration guide सीखें। Practical tips और code examples शामिल हैं।