import { createProxyMiddleware } from 'http-proxy-middleware';
export function useProxy(options, app, logger) {
    for (const path of Object.keys(options)) {
        let opts = options[path];
        if (typeof opts === 'string') {
            opts = { target: opts, changeOrigin: true };
        }
        const proxyMiddleware = createProxyMiddleware(opts);
        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);
                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;
    }
    const options = config.proxy;
    useProxy(options, devSeverContext.app(), logger);
}
//# sourceMappingURL=proxy.js.map