import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb'; import { unmarshall } from '@aws-sdk/util-dynamodb'; const client = new DynamoDBClient({ region: 'us-east-1' }); export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => { const tag = event.queryStringParameters?.tag || ''; const params = { TableName: 'BlogPosts', FilterExpression: tag ? 'contains(tags, :tag)' : undefined, ExpressionAttributeValues: tag ? { ':tag': { S: tag } } : undefined, }; try { const result = await client.send(new ScanCommand(params)); const posts = result.Items?.map(item => unmarshall(item)) || []; return { statusCode: 200, body: JSON.stringify(posts), }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ error: 'Failed to fetch posts' }), }; } };
import type { NextRequest, NextResponse } from 'next/server'; export const config = { runtime: 'edge', }; export default async function handler(req: NextRequest): Promise<NextResponse> { const url = new URL(req.url); const tag = url.pathname.slice(1); // e.g., "tech" from "/tech" const country = req.headers.get('x-vercel-ip-country') || 'US'; if (tag) { url.pathname = '/api/posts'; url.searchParams.set('tag', tag); url.searchParams.set('country', country); const response = await fetch(url); return new NextResponse(response.body, { status: response.status, headers: { 'x-country': country }, }); } return new NextResponse('Invalid tag', { status: 400 }); }
import type { NextRequest, NextResponse } from 'next/server'; export const config = { runtime: 'edge', }; export default async function handler(req: NextRequest): Promise<NextResponse> { const url = new URL(req.url); const tag = url.pathname.slice(1); if (tag) { // Bad: Slow API and heavy loop const posts = await fetch('https://slow-api.com/posts').then(res => res.json()); const filteredPosts = posts .filter((post: any) => post.tags.includes(tag)) .map((post: any) => heavyComputation(post)); return new NextResponse(JSON.stringify(filteredPosts), { status: 200 }); } return new NextResponse('Invalid tag', { status: 400 }); } function heavyComputation(post: any): string { let result = ''; for (let i = 0; i < 1000000; i++) { result += post.title; } return result; }