proxy-events.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { Debug } from '../../debug.js';
  2. import { getFunctionName } from '../../utils/function.js';
  3. import { definePlugin } from '../define-plugin.js';
  4. const debug = Debug.extend('proxy-events-plugin');
  5. /**
  6. * Implements option.on object to subscribe to `httpxy` events.
  7. *
  8. * @example
  9. * ```js
  10. * createProxyMiddleware({
  11. * on: {
  12. * error: (error, req, res, target) => {},
  13. * proxyReq: (proxyReq, req, res, options) => {},
  14. * proxyReqWs: (proxyReq, req, socket, options) => {},
  15. * proxyRes: (proxyRes, req, res) => {},
  16. * open: (proxySocket) => {},
  17. * close: (proxyRes, proxySocket, proxyHead) => {},
  18. * start: (req, res, target) => {},
  19. * end: (req, res, proxyRes) => {},
  20. * econnreset: (error, req, res, target) => {},
  21. * }
  22. * });
  23. * ```
  24. */
  25. export const proxyEventsPlugin = definePlugin((proxyServer, options) => {
  26. if (!options.on) {
  27. return;
  28. }
  29. // hoist variable here for better typing
  30. let eventName;
  31. // for in provide better typing than Object.entries()
  32. for (eventName in options.on) {
  33. if (Object.prototype.hasOwnProperty.call(options.on, eventName)) {
  34. const handler = options.on[eventName];
  35. if (!handler) {
  36. continue;
  37. }
  38. debug(`register event handler: "${eventName}" -> "${getFunctionName(handler)}"`);
  39. proxyServer.on(eventName, handler);
  40. }
  41. }
  42. });