@farmfe/core
Version:
Farm is a extremely fast web build tool written in Rust. Farm can start a project in milliseconds and perform HMR within 10ms, making it much faster than similar tools like webpack and vite.
83 lines • 3.06 kB
JavaScript
import { createProxyMiddleware } from 'http-proxy-middleware';
export function useProxy(options, devSeverContext, logger) {
const proxyOption = options['proxy'];
for (const path of Object.keys(proxyOption)) {
let opts = proxyOption[path];
if (typeof opts === 'string') {
opts = { target: opts, changeOrigin: true };
}
const proxyMiddleware = createProxyMiddleware(opts);
const server = devSeverContext.server;
const hmrOptions = options.hmr;
if (server) {
server.on('upgrade', (req, socket, head) => {
if (req.url === hmrOptions.path)
return;
for (const path in options.proxy) {
const opts = proxyOption[path];
if (opts.ws ||
opts.target?.toString().startsWith('ws:') ||
opts.target?.toString().startsWith('wss:')) {
const proxy = createProxyMiddleware(opts);
if (opts.pathRewrite) {
const fromPath = Object.keys(opts.pathRewrite)[0];
const toPath = opts.pathRewrite[fromPath];
req.url = rewritePath(req.url, fromPath, toPath);
}
proxy.upgrade(req, socket, head);
return;
}
}
});
}
const errorHandlerMiddleware = async (ctx, next) => {
try {
await new Promise((resolve, reject) => {
proxyMiddleware(ctx.req, ctx.res, (err) => {
if (err) {
reject(err);
}
else {
resolve();
}
});
});
await next();
}
catch (err) {
logger.error(`Error in proxy for path ${path}: \n ${err.stack}`);
}
};
try {
if (path.length > 0) {
const pathRegex = new RegExp(path);
const app = devSeverContext.app();
app.use((ctx, next) => {
if (pathRegex.test(ctx.path)) {
return errorHandlerMiddleware(ctx, next);
}
return next();
});
}
}
catch (err) {
logger.error(`Error setting proxy for path ${path}: \n ${err.stack}`);
}
}
}
export function proxy(devSeverContext) {
const { config, logger } = devSeverContext;
if (!config.proxy) {
return;
}
useProxy(config, devSeverContext, logger);
}
function rewritePath(path, fromPath, toPath) {
if (fromPath instanceof RegExp) {
return path.replace(fromPath, toPath);
}
else {
return path.replace(new RegExp(fromPath), toPath);
}
}
//# sourceMappingURL=proxy.js.map