Untitled
unknown
plain_text
2 years ago
2.1 kB
15
Indexable
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const PORT = process.env.PORT || 8080;
// Define target URLs
const serviceUrls = {
HOME: process.env.HOME_URL || "http://prd-microfront-loja-home.domain-microfront-loja.svc.cluster.local",
CHECKOUT: process.env.CHECKOUT_URL || "http://prd-microfront-loja-checkout.domain-microfront-loja.svc.cluster.local",
PRODUCT: process.env.PRODUCT_URL || "http://prd-microfront-loja-product.domain-microfront-loja.svc.cluster.local",
CART: process.env.CART_URL || "http://prd-microfront-loja-cart.domain-microfront-loja.svc.cluster.local",
};
console.log(serviceUrls)
// Create a generic proxy middleware function
function createProxy(path, target) {
return createProxyMiddleware(path, {
target,
changeOrigin: true,
pathRewrite: {
[`^${path}`]: '',
},
onProxyRes(proxyRes) {
proxyRes.headers['Access-Control-Allow-Origin'] = '*';
proxyRes.headers['Cache-Control'] = 'no-cache';
},
onProxyReq(proxyReq) {
proxyReq.setHeader('Accept', '*/*');
},
});
}
// Create proxy middleware instances
const homeProxy = createProxy('/', serviceUrls.HOME);
const cartProxy = createProxy('/cart', serviceUrls.CART);
const checkoutProxy = createProxy('/checkout', serviceUrls.CHECKOUT);
const productProxy = createProxy('/product/:slug', serviceUrls.PRODUCT);
// Middleware for handling static files
function handleStaticFiles(req, res, next) {
if (req.url.endsWith('.js') || req.url.endsWith('.css')) {
// Handle static files differently if needed
// Example: serve from a different location
} else {
next();
}
}
// Health check endpoint
function healthCheck(_, res) {
res.send('Hello, I\'m alive!');
}
// Apply middleware
app.use('/health-check', healthCheck);
app.use(handleStaticFiles); // Handle static files before proxies
app.use('/cart', cartProxy);
app.use('/checkout', checkoutProxy);
app.use('/product', productProxy);
app.use('/', homeProxy);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Editor is loading...