import { Provide, Config, ALL } from '@midwayjs/decorator';
import { IWebMiddleware, IMidwayWebNext } from '@midwayjs/web';
import { Context } from 'egg';
import { MyConfig } from '../config/types';
@Provide()
export class ContentPathMiddleware implements IWebMiddleware {
@Config(ALL)
config: MyConfig;
resolve() {
return async (ctx: Context, next: IMidwayWebNext) => {
const { contextPath } = this.config;
if (contextPath) {
const reg = new RegExp(contextPath);
const { url } = ctx.req;
if (reg.test(url)) {
// 去掉 content path
const path = ctx.req.url.replace(reg, '');
// console.log('去掉 contentPath > ', path);
if (path) ctx.req.url = path;
}
}
const { url, method, httpVersion, headers = {} } = ctx.req;
const { body } = ctx.request;
console.log( '>>> ', method, httpVersion, headers['content-type'], url, JSON.stringify(body) );
await next();
console.log( '<<< ', method, ctx.response.headers['content-type'], url, JSON.stringify(ctx.body) );
};
}
}