proxy.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import type { HttpProxy, ProxyOptions } from 'vite';
  2. import { bgRed, bgYellow, green, lightBlue } from 'kolorist';
  3. import { consola } from 'consola';
  4. import { createServiceConfig } from '../../src/utils/service';
  5. /**
  6. * Set http proxy
  7. *
  8. * @param env - The current env
  9. * @param enable - If enable http proxy
  10. */
  11. export function createViteProxy(env: Env.ImportMeta, enable: boolean) {
  12. const isEnableHttpProxy = enable && env.VITE_HTTP_PROXY === 'Y';
  13. if (!isEnableHttpProxy) return undefined;
  14. const isEnableProxyLog = env.VITE_PROXY_LOG === 'Y';
  15. const { baseURL, proxyPattern, other } = createServiceConfig(env);
  16. const proxy: Record<string, ProxyOptions> = createProxyItem({ baseURL, proxyPattern }, isEnableProxyLog);
  17. other.forEach(item => {
  18. Object.assign(proxy, createProxyItem(item, isEnableProxyLog));
  19. });
  20. return proxy;
  21. }
  22. function createProxyItem(item: App.Service.ServiceConfigItem, enableLog: boolean) {
  23. const proxy: Record<string, ProxyOptions> = {};
  24. proxy[item.proxyPattern] = {
  25. target: item.baseURL,
  26. changeOrigin: true,
  27. configure: (_proxy: HttpProxy.Server, options: ProxyOptions) => {
  28. _proxy.on('proxyReq', (_proxyReq, req, _res) => {
  29. if (!enableLog) return;
  30. const requestUrl = `${lightBlue('[proxy url]')}: ${bgYellow(` ${req.method} `)} ${green(`${item.proxyPattern}${req.url}`)}`;
  31. const proxyUrl = `${lightBlue('[real request url]')}: ${green(`${options.target}${req.url}`)}`;
  32. consola.log(`${requestUrl}\n${proxyUrl}`);
  33. });
  34. _proxy.on('error', (_err, req, _res) => {
  35. if (!enableLog) return;
  36. consola.log(bgRed(`Error: ${req.method} `), green(`${options.target}${req.url}`));
  37. });
  38. },
  39. rewrite: path => path.replace(new RegExp(`^${item.proxyPattern}`), '')
  40. };
  41. return proxy;
  42. }