1+ import type { NextApiRequest , NextApiResponse } from 'next' ;
2+
3+ const BACKEND_URL = process . env . BACKEND_URL || 'http://localhost:8000' ;
4+
5+ export default async function handler ( req : NextApiRequest , res : NextApiResponse ) {
6+ const { method } = req ;
7+
8+ try {
9+ let url = `${ BACKEND_URL } /volunteer-data` ;
10+ let fetchOptions : RequestInit = {
11+ method,
12+ headers : {
13+ 'Content-Type' : 'application/json' ,
14+ // Forward authorization header if present
15+ ...( req . headers . authorization && {
16+ 'Authorization' : req . headers . authorization ,
17+ } ) ,
18+ } ,
19+ } ;
20+
21+ // Handle different HTTP methods
22+ switch ( method ) {
23+ case 'POST' :
24+ // Create volunteer data
25+ fetchOptions . body = JSON . stringify ( req . body ) ;
26+ break ;
27+
28+ case 'GET' :
29+ // Get volunteer data - handle query parameters
30+ if ( req . query . id ) {
31+ url = `${ BACKEND_URL } /volunteer-data/${ req . query . id } ` ;
32+ } else if ( req . query . user_id ) {
33+ url = `${ BACKEND_URL } /volunteer-data/user/${ req . query . user_id } ` ;
34+ }
35+ // If no specific query, it will get all volunteer data
36+ break ;
37+
38+ case 'PUT' :
39+ // Update volunteer data
40+ if ( req . query . id ) {
41+ url = `${ BACKEND_URL } /volunteer-data/${ req . query . id } ` ;
42+ fetchOptions . body = JSON . stringify ( req . body ) ;
43+ } else {
44+ return res . status ( 400 ) . json ( { error : 'ID required for PUT request' } ) ;
45+ }
46+ break ;
47+
48+ case 'DELETE' :
49+ // Delete volunteer data
50+ if ( req . query . id ) {
51+ url = `${ BACKEND_URL } /volunteer-data/${ req . query . id } ` ;
52+ } else {
53+ return res . status ( 400 ) . json ( { error : 'ID required for DELETE request' } ) ;
54+ }
55+ break ;
56+
57+ default :
58+ return res . status ( 405 ) . json ( { error : `Method ${ method } not allowed` } ) ;
59+ }
60+
61+ // Make request to FastAPI backend
62+ const response = await fetch ( url , fetchOptions ) ;
63+ const data = await response . json ( ) ;
64+
65+ // Forward the response status and data
66+ res . status ( response . status ) . json ( data ) ;
67+
68+ } catch ( error ) {
69+ console . error ( 'API proxy error:' , error ) ;
70+ res . status ( 500 ) . json ( {
71+ error : 'Internal server error' ,
72+ details : error instanceof Error ? error . message : 'Unknown error'
73+ } ) ;
74+ }
75+ }
0 commit comments