@@ -4,23 +4,45 @@ const httpProxy = require("http-proxy");
44const proxy = httpProxy . createProxyServer ( ) ;
55const app = express ( ) ;
66
7+ const AUTH_SERVICE_HOST = process . env . AUTH_SERVICE_HOST || "auth" ;
8+ const AUTH_SERVICE_PORT = process . env . AUTH_SERVICE_PORT || "3000" ;
9+ const PRODUCT_SERVICE_HOST = process . env . PRODUCT_SERVICE_HOST || "product" ;
10+ const PRODUCT_SERVICE_PORT = process . env . PRODUCT_SERVICE_PORT || "3001" ;
11+ const ORDER_SERVICE_HOST = process . env . ORDER_SERVICE_HOST || "order" ;
12+ const ORDER_SERVICE_PORT = process . env . ORDER_SERVICE_PORT || "3002" ;
13+
14+ const AUTH_SERVICE_URL =
15+ process . env . AUTH_SERVICE_URL || `http://${ AUTH_SERVICE_HOST } :${ AUTH_SERVICE_PORT } ` ;
16+ const PRODUCT_SERVICE_URL =
17+ process . env . PRODUCT_SERVICE_URL ||
18+ `http://${ PRODUCT_SERVICE_HOST } :${ PRODUCT_SERVICE_PORT } ` ;
19+ const ORDER_SERVICE_URL =
20+ process . env . ORDER_SERVICE_URL || `http://${ ORDER_SERVICE_HOST } :${ ORDER_SERVICE_PORT } ` ;
21+
22+ proxy . on ( "error" , ( err , req , res ) => {
23+ console . error ( "Proxy error:" , err . message ) ;
24+ if ( ! res . headersSent ) {
25+ res . status ( 502 ) . json ( { message : "Service unavailable" } ) ;
26+ }
27+ } ) ;
28+
729// Route requests to the auth service
830app . use ( "/auth" , ( req , res ) => {
9- proxy . web ( req , res , { target : "http://auth:3000" } ) ;
31+ proxy . web ( req , res , { target : AUTH_SERVICE_URL } ) ;
1032} ) ;
1133
1234// Route requests to the product service
1335app . use ( "/products" , ( req , res ) => {
14- proxy . web ( req , res , { target : "http://product:3001" } ) ;
36+ proxy . web ( req , res , { target : PRODUCT_SERVICE_URL } ) ;
1537} ) ;
1638
1739// Route requests to the order service
1840app . use ( "/orders" , ( req , res ) => {
19- proxy . web ( req , res , { target : "http://order:3002" } ) ;
41+ proxy . web ( req , res , { target : ORDER_SERVICE_URL } ) ;
2042} ) ;
2143
2244// Start the server
23- const port = process . env . PORT || 3003 ;
45+ const port = Number ( process . env . PORT ) || 3003 ;
2446app . listen ( port , ( ) => {
2547 console . log ( `API Gateway listening on port ${ port } ` ) ;
2648} ) ;
0 commit comments