mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-04 23:59:31 +01:00
feat: add middleware and error handling
Co-Authored-By: G <butaeff@gmail.com>
This commit is contained in:
1 parent
c97ce425b1
commit
6c2e23fcab
4 files changed
+239
-21
No files matched your search
@@ -1,40 +1,110 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
import { connectDB } from '@/src/lib/mongodb';
|
||||
import { Consultation } from '@/src/lib/models/consultation';
|
||||
import { rateLimit } from '@/src/lib/rate-limit';
|
||||
import { CustomerSchema } from '@/src/lib/schemas/customer';
|
||||
import { createErrorResponse } from '@/src/lib/schemas/errors';
|
||||
import { validateApiKey } from '@/src/lib/middleware/auth';
|
||||
import { monitorRequest } from '@/src/lib/middleware/monitoring';
|
||||
import { EmailService } from '@/src/lib/email/service';
|
||||
import { ZodError } from 'zod';
|
||||
|
||||
const limiter = rateLimit({
|
||||
limit: 5, // 5 requests per interval
|
||||
interval: 60 * 1000, // 1 minute
|
||||
limit: process.env.NODE_ENV === 'test' ? 3 : 5,
|
||||
interval: process.env.NODE_ENV === 'test' ? 1000 : 60 * 1000,
|
||||
uniqueTokenPerInterval: 500,
|
||||
});
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const emailService = new EmailService();
|
||||
|
||||
async function handler(req: NextRequest) {
|
||||
let body;
|
||||
try {
|
||||
const { isRateLimited } = await limiter.check('CONSULTATION_FORM');
|
||||
// Validate API key first
|
||||
const authResponse = await validateApiKey(req);
|
||||
if (authResponse) {
|
||||
return authResponse;
|
||||
}
|
||||
|
||||
// Check rate limit
|
||||
const rateLimitKey = 'CONSULTATION_FORM';
|
||||
const { isRateLimited } = await limiter.check(rateLimitKey);
|
||||
if (isRateLimited) {
|
||||
throw Object.assign(new Error('Rate limit exceeded'), { code: 'RATE_LIMIT' });
|
||||
}
|
||||
|
||||
const { name, email, message } = await req.json();
|
||||
await connectDB();
|
||||
body = await req.json();
|
||||
const validatedData = CustomerSchema.parse(body);
|
||||
|
||||
const consultation = await Consultation.create({
|
||||
name,
|
||||
email,
|
||||
message,
|
||||
});
|
||||
// Connect to DB (skipped in test environment)
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
await connectDB();
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, id: consultation._id });
|
||||
const consultation = await Consultation.create(validatedData);
|
||||
|
||||
// Send emails asynchronously
|
||||
try {
|
||||
await Promise.all([
|
||||
emailService.sendWelcomeEmail(validatedData),
|
||||
emailService.sendAdminNotification(validatedData),
|
||||
]);
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send emails:', emailError);
|
||||
// Don't return error response, continue with success
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ success: true, id: consultation._id }),
|
||||
{
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error('Consultation submission error:', error);
|
||||
|
||||
if (error.code === 'RATE_LIMIT') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Rate limit exceeded. Please try again later.' },
|
||||
{ status: 429 }
|
||||
return new Response(
|
||||
JSON.stringify(createErrorResponse(
|
||||
'Rate limit exceeded. Please try again later.',
|
||||
'RATE_LIMIT'
|
||||
)),
|
||||
{
|
||||
status: 429,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
console.error('Consultation submission error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to submit consultation' },
|
||||
{ status: 500 }
|
||||
if (error instanceof ZodError) {
|
||||
return new Response(
|
||||
JSON.stringify(createErrorResponse(
|
||||
'Validation failed',
|
||||
'VALIDATION_ERROR',
|
||||
error.errors.map(err => ({
|
||||
field: err.path.join('.'),
|
||||
message: err.message
|
||||
}))
|
||||
)),
|
||||
{
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify(createErrorResponse(
|
||||
'Failed to submit consultation',
|
||||
'INTERNAL_ERROR'
|
||||
)),
|
||||
{
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = (req: NextRequest) => monitorRequest(req, handler);
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createErrorResponse } from '../schemas/errors';
|
||||
|
||||
const API_KEY = process.env.API_KEY || 'development-key';
|
||||
|
||||
export async function validateApiKey(req: Request) {
|
||||
// Skip validation during build time
|
||||
if (process.env.NODE_ENV === 'production' && process.env.NEXT_PHASE === 'phase-production-build') {
|
||||
return;
|
||||
}
|
||||
|
||||
const apiKey = req.headers.get('x-api-key');
|
||||
|
||||
if (!apiKey) {
|
||||
return new Response(
|
||||
JSON.stringify(createErrorResponse(
|
||||
'API key is required',
|
||||
'UNAUTHORIZED'
|
||||
)),
|
||||
{
|
||||
status: 401,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (apiKey !== API_KEY) {
|
||||
return new Response(
|
||||
JSON.stringify(createErrorResponse(
|
||||
'Invalid API key',
|
||||
'UNAUTHORIZED'
|
||||
)),
|
||||
{
|
||||
status: 401,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
interface RequestMetrics {
|
||||
path: string;
|
||||
method: string;
|
||||
startTime: number;
|
||||
duration?: number;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
const metrics: RequestMetrics[] = [];
|
||||
|
||||
export async function monitorRequest<T extends Request | NextRequest>(
|
||||
req: T,
|
||||
handler: (req: T) => Promise<Response>
|
||||
) {
|
||||
const startTime = performance.now();
|
||||
const getPath = (req: Request | NextRequest): string => {
|
||||
if ('nextUrl' in req) {
|
||||
return req.nextUrl.pathname;
|
||||
}
|
||||
try {
|
||||
return new URL(req.url).pathname;
|
||||
} catch {
|
||||
// If URL parsing fails, try to extract path from url string
|
||||
const urlPath = req.url.split('?')[0];
|
||||
return urlPath.startsWith('http') ? new URL(urlPath).pathname : urlPath;
|
||||
}
|
||||
};
|
||||
|
||||
const path = getPath(req);
|
||||
const method = req.method;
|
||||
|
||||
try {
|
||||
const response = process.env.NODE_ENV === 'test'
|
||||
? await handler(req)
|
||||
: await Promise.race([
|
||||
handler(req),
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Request timeout')), 30000)
|
||||
)
|
||||
]);
|
||||
|
||||
const duration = performance.now() - startTime;
|
||||
|
||||
// Store metrics
|
||||
metrics.push({
|
||||
path,
|
||||
method,
|
||||
startTime,
|
||||
duration,
|
||||
status: response.status
|
||||
});
|
||||
|
||||
// Log performance metrics
|
||||
console.info(`API ${method} ${path} completed in ${duration.toFixed(2)}ms with status ${response.status}`);
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
const duration = performance.now() - startTime;
|
||||
|
||||
// Store error metrics
|
||||
metrics.push({
|
||||
path,
|
||||
method,
|
||||
startTime,
|
||||
duration,
|
||||
status: 500
|
||||
});
|
||||
|
||||
console.error(`API ${method} ${path} failed after ${duration.toFixed(2)}ms:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Utility to get recent metrics
|
||||
export function getRecentMetrics(minutes: number = 5): RequestMetrics[] {
|
||||
const cutoff = Date.now() - (minutes * 60 * 1000);
|
||||
return metrics.filter(m => m.startTime > cutoff);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export type ErrorCode =
|
||||
| 'UNAUTHORIZED'
|
||||
| 'VALIDATION_ERROR'
|
||||
| 'RATE_LIMIT'
|
||||
| 'DATABASE_ERROR'
|
||||
| 'INTERNAL_ERROR'
|
||||
| 'NOT_FOUND';
|
||||
|
||||
export interface ErrorDetail {
|
||||
field?: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ErrorResponse {
|
||||
error: string;
|
||||
code: ErrorCode;
|
||||
details?: ErrorDetail[];
|
||||
}
|
||||
|
||||
export function createErrorResponse(
|
||||
message: string,
|
||||
code: ErrorCode,
|
||||
details?: ErrorDetail[]
|
||||
): ErrorResponse {
|
||||
return {
|
||||
error: message,
|
||||
code,
|
||||
...(details && { details }),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user