-
Notifications
You must be signed in to change notification settings - Fork 343
Expand file tree
/
Copy pathroute.ts
More file actions
85 lines (73 loc) · 2.54 KB
/
Copy pathroute.ts
File metadata and controls
85 lines (73 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// POST /api/goals/[id]/add - Add funds to a savings goal
import { NextRequest, NextResponse } from 'next/server';
import { buildAddToGoalTx } from '@/lib/contracts/savings-goals';
import { getSessionFromRequest, getPublicKeyFromSession } from '@/lib/auth/session';
import {
createValidationError,
createAuthenticationError,
handleUnexpectedError
} from '@/lib/errors/api-errors';
import {
validateAmount,
validateGoalId
} from '@/lib/validation/savings-goals';
import { ApiSuccessResponse } from '@/lib/types/savings-goals';
import { auditLog, createAuditEvent, extractIp, AuditAction } from '@/lib/audit';
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
// Authenticate user
const session = getSessionFromRequest(request);
if (!session) {
return createAuthenticationError('Authentication required', 'Please provide a valid session');
}
let publicKey: string;
try {
publicKey = getPublicKeyFromSession(session);
} catch (error) {
return createAuthenticationError('Invalid session', 'Session does not contain a valid public key');
}
// Validate goal ID from URL params
const { id: goalId } = await params;
const goalIdValidation = validateGoalId(goalId);
if (!goalIdValidation.isValid) {
return createValidationError('Invalid goal ID', goalIdValidation.error);
}
// Parse request body
let body;
try {
body = await request.json();
} catch (error) {
return createValidationError('Invalid request body', 'Request body must be valid JSON');
}
const { amount } = body;
// Validate amount
if (amount === undefined || amount === null) {
return createValidationError('Missing required field', 'Amount is required');
}
const amountValidation = validateAmount(amount);
if (!amountValidation.isValid) {
return createValidationError('Invalid amount', amountValidation.error);
}
// Build transaction
const result = await buildAddToGoalTx(publicKey, goalId, amount);
// Log goal funding
await auditLog(
createAuditEvent(AuditAction.GOAL_ADD_FUNDS, 'success', {
address: publicKey,
ip: extractIp(request),
resource: goalId,
metadata: { amount },
})
);
// Return success response
const response: ApiSuccessResponse = {
xdr: result.xdr
};
return NextResponse.json(response, { status: 200 });
} catch (error) {
return handleUnexpectedError(error);
}
}