Files
ZYZ/web-server/app/middleware/egg-proxy.ts
2026-03-13 01:38:40 +00:00

59 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import c2k = require('koa-connect');
import { createProxyMiddleware, Options as ContextOptions } from 'http-proxy-middleware';
import * as micromatch from 'micromatch';
import * as isGlob from 'is-glob';
import { Context } from 'egg';
// 扩展Request接口添加rawBody属性
declare module 'egg' {
interface Request {
rawBody: string;
}
}
function match(context: string, path: string): boolean {
// single path
if (!isGlob(context)) {
return path.indexOf(context) === 0;
} else {
// single glob path
const matches = micromatch([path], context);
return matches?.length > 0;
}
}
export interface Options {
[contextName: string]: ContextOptions;
}
export default function (options: Options) {
return async (ctx: Context, next: () => Promise<any>) => {
for (const context of Object.keys(options)) {
if (match(context, ctx.path)) {
const contextOptions: ContextOptions = options[context];
const { onProxyReq } = contextOptions;
await c2k(
createProxyMiddleware(context, {
...contextOptions,
onProxyReq(proxyReq, req, res) {
if (onProxyReq && typeof onProxyReq === 'function') {
onProxyReq(proxyReq, req, res);
}
// reset rawBody after bodyparser
const { rawBody, body: requestBody } = ctx.request;
if (requestBody && rawBody) {
proxyReq.setHeader('Content-Length', Buffer.byteLength(rawBody));
proxyReq.write(rawBody);
proxyReq.end();
}
return proxyReq;
},
}) as any
)(ctx as any, next);
}
}
await next();
};
}