Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.6 kB
2
Indexable
Never
const express = require('express')
const { createProxyMiddleware } = require('http-proxy-middleware')

const app = express()

const PORT = 80

const HOME_URL = 'http://stg-microfront-loja-home.domain-microfront-loja.svc.cluster.local'
const CHECKOUT_URL = 'http://stg-microfront-loja-checkout.domain-microfront-loja.svc.cluster.local'
const PRODUCT_URL = 'http://stg-microfront-loja-product.domain-microfront-loja.svc.cluster.local'
const CART_URL = 'http://stg-microfront-loja-cart.domain-microfront-loja.svc.cluster.local'

const homeProxy = createProxyMiddleware('/', {
  target: HOME_URL,
  changeOrigin: true,
  pathRewrite: {
    '^/': '',
  },
  onProxyRes(proxyRes) {
    proxyRes.headers['Access-Control-Allow-Origin'] = '*'
    proxyRes.headers['Cache-Control'] = 'no-cache'
  },
  onProxyReq: (proxyReq) => {
    proxyReq.setHeader('Accept', '*/*')
  },
})

const cartProxy = createProxyMiddleware('/cart', {
  target: CART_URL,
  changeOrigin: true,
  pathRewrite: {
    '^/cart': '',
  },
})

const cartProxyFiles = createProxyMiddleware('/cart/**', {
  target: CART_URL,
  changeOrigin: true,
})

const checkoutProxy = createProxyMiddleware('/checkout', {
  target: CHECKOUT_URL,
  changeOrigin: true,
  pathRewrite: {
    '^/checkout': '',
  },
})

const checkoutProxyFiles = createProxyMiddleware('/checkout/**', {
  target: CHECKOUT_URL,
  changeOrigin: true,
})

const productProxy = createProxyMiddleware('/product', {
  target: PRODUCT_URL,
  changeOrigin: true,
  pathRewrite: {
    '^/product/:slug': '',
  },
})

const productProxyFiles = createProxyMiddleware('/product/**', {
  target: PRODUCT_URL,
  changeOrigin: true,
})

function handleCart(req, res, next) {
  const url = req.url

  if (url.endsWith('.js') || url.endsWith('.css'))
    cartProxyFiles(req, res, next)

  else
    cartProxy(req, res, next)
}

function handleCheckout(req, res, next) {
  const url = req.url

  if (url.endsWith('.js') || url.endsWith('.css'))
    checkoutProxyFiles(req, res, next)

  else
    checkoutProxy(req, res, next)
}

function handleProduct(req, res, next) {
  const url = req.url

  if (url.endsWith('.js') || url.endsWith('.css'))
    productProxyFiles(req, res, next)

  else
    productProxy(req, res, next)
}

function checkUrl(req, res, next) {
  const url = req.host + req.path

  if (url.endsWith('sw.js'))
    return

  next()
}

function healthCheck(_, res) {
  res.send('Hello, I\'m alive!')
}

app.use(checkUrl)

app.use('/product', handleProduct)
app.use('/checkout', handleCheckout)
app.use('/health-check', healthCheck)
app.use('/cart', handleCart)
app.use('/', homeProxy)

app.listen(PORT)