我的Express应用程序中有很多String resultString = IOUtils.toString(userInputStream, "UTF-8");
,它们变得凌乱而复杂,并且到处都有配置。因此,我想将它们移至单独的模块,以便于测试。
所以我的中间件包装器有这个app.use(...)
基类:
Middleware.ts
和一个子类,例如export default abstract class Middleware {
public run(): express.RequestHandler {
try {
return this.runImpl;
}
catch (err) {
log("Failed to init middleware " + err);
throw err;
}
}
public abstract runImpl(): express.RequestHandler;
}
用于提供静态文件:
StaticMiddleware.ts
最后,export class StaticMiddleware extends Middleware {
public runImp(): express.RequestHandler {
// this is a simple example, but most middleware are more
// complicated, but everything is encapsulated here
return express.static("path");
}
}
export default new StaticMiddleware().run;
Express应用程序本身非常干净:
app.ts
但是在运行时出现错误:
TypeError:app.use()需要一个中间件功能
请注意,可以更改上面的方法签名,所以我可以使用这种形式:
import staticMiddleware from "./StaticMiddleware";
import fooMiddleware from "./FooMiddleware";
import barMiddleware from "./BarMiddleware";
app.use(staticMiddleware());
app.use(fooMiddleware());
app.use(barMiddleware());
但是,这对于维护人员来说是令人惊讶的,并且容易被破坏。我想要正常的签名:
app.use(staticMiddleware);