Ts.ED框架自定义平台适配器开发指南
什么是平台适配器
平台适配器是Ts.ED框架中连接核心功能与不同Web框架的桥梁。它允许开发者使用Ts.ED的装饰器和抽象API,同时底层可以运行在Express、Koa、Fastify等不同Web框架上。
为什么需要自定义适配器
虽然Ts.ED已经内置了常见框架的适配器,但在以下场景可能需要自定义适配器:
- 需要集成Ts.ED不支持的新兴Web框架
- 现有适配器不能满足特殊需求
- 需要对底层框架进行深度定制
适配器核心架构
核心抽象类
Ts.ED提供了PlatformAdapter
抽象类作为所有适配器的基类,它定义了适配器必须实现的核心接口:
abstract class PlatformAdapter<T = any> {
abstract NAME: string;
abstract createApp(): {app: T; callback(): any};
abstract useContext(): void;
abstract mapHandler(handler: Function, metadata: PlatformHandlerMetadata): any;
abstract mapLayers(layers: PlatformLayer[]): void;
abstract bodyParser(type: string, options: any): any;
abstract statics(endpoint: string, options: any): any;
}
关键组件
- PlatformHandler - 处理请求的核心逻辑
- PlatformRequest - 封装框架原生请求对象
- PlatformResponse - 封装框架原生响应对象
- Context管理 - 维护请求上下文
开发步骤详解
1. 初始化项目结构
建议采用以下目录结构:
src/
├── components/ // 核心组件
│ └── PlatformCustom.ts
├── interfaces/ // 类型定义
│ └── PlatformCustomSettings.ts
├── services/ // 服务实现
│ ├── PlatformCustomHandler.ts
│ ├── PlatformCustomRequest.ts
│ └── PlatformCustomResponse.ts
├── middlewares/ // 中间件
│ └── staticsMiddleware.ts
└── index.ts // 入口文件
2. 实现核心适配器类
import {PlatformAdapter} from "@tsed/platform-http";
export class PlatformCustom extends PlatformAdapter<CustomFrameworkApp> {
readonly NAME = "custom";
createApp() {
const app = new CustomFramework();
return {
app,
callback: () => app.handle.bind(app)
};
}
useContext() {
const invoke = createContext();
this.app.use(async (req, res, next) => {
const $ctx = invoke({req, res});
await $ctx.start();
req.$ctx = $ctx;
res.on("finish", () => $ctx.finish());
next();
});
}
}
3. 请求/响应映射
需要实现请求和响应对象的适配:
// PlatformCustomRequest.ts
export class PlatformCustomRequest extends PlatformRequest {
get protocol(): string {
return this.raw.req.protocol;
}
get host(): string {
return this.raw.req.get("host");
}
}
// PlatformCustomResponse.ts
export class PlatformCustomResponse extends PlatformResponse {
status(code: number) {
this.raw.status(code);
return this;
}
}
4. 路由处理
实现路由映射逻辑:
mapLayers(layers: PlatformLayer[]) {
layers.forEach(layer => {
switch(layer.method) {
case "get":
case "post":
this.app[layer.method](layer.path, ...layer.handlers);
break;
case "statics":
this.app.use(layer.path, serveStatic(layer.path, layer.options));
}
});
}
5. 处理器映射
将Ts.ED处理器转换为框架处理器:
mapHandler(handler: Function, metadata: PlatformHandlerMetadata) {
if (metadata.type === "middleware") {
return (req, res, next) => {
const $ctx = req.$ctx;
$ctx.next = next;
handler($ctx);
};
}
return (req, res) => {
const $ctx = req.$ctx;
handler($ctx).then(() => {
if (!$ctx.isDone()) {
res.end();
}
});
};
}
高级主题
上下文管理
Ts.ED使用异步上下文(async_hooks)来维护请求生命周期中的状态。适配器需要确保:
- 每个请求创建新的上下文
- 上下文在整个请求链中可访问
- 请求结束时清理上下文
异常处理
适配器需要正确处理以下异常情况:
- 同步异常
- 异步异常
- 中间件异常
- 处理器异常
性能优化
对于高性能场景,可以考虑:
- 避免不必要的对象包装
- 使用框架原生特性
- 优化中间件链
测试策略
单元测试
测试各个组件独立功能:
describe("PlatformCustomRequest", () => {
it("should get protocol", () => {
const req = new PlatformCustomRequest(mockReq);
expect(req.protocol).toBe("http");
});
});
集成测试
使用@tsed/platform-test-sdk
进行完整测试:
import {PlatformTestSdk} from "@tsed/platform-test-sdk";
PlatformTestSdk.create({
adapter: PlatformCustom,
server: TestServer
}).test("handlers");
测试套件会验证:
- 路由处理
- 参数绑定
- 响应处理
- 中间件
- 错误处理
最佳实践
- 保持兼容性:尽量与现有适配器保持相同行为
- 文档完善:记录所有框架特定行为
- 性能基准:与原生框架对比性能
- 渐进实现:先实现核心功能,再逐步完善
总结
开发Ts.ED平台适配器需要深入理解Ts.ED的核心抽象和目标Web框架的特性。通过实现PlatformAdapter接口和配套组件,可以将Ts.ED的强大功能带到任何Web框架上。
良好的适配器应该做到:
- 完整实现所有必需接口
- 正确处理各种边缘情况
- 保持与Ts.ED核心的一致性
- 提供良好的性能表现
通过本文的指导,开发者可以创建出高质量的自定义平台适配器,扩展Ts.ED的框架支持能力。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考