typescript - 使用 Typescript 类语法在 Oak 中获取当前上下文
问题描述
我在使用 Deno 和 Oak 的情况下苦苦挣扎。const xy = () => {}
大多数教程在分隔控制器和路由时都使用导出语法。
在路线中,他们通常有类似的东西router.get("/the-route", xy)
,这很好,但有几个我想避免的警告。
我不想要的
看这个例子:
const someController = async ({
request,
response,
}: {
request: any;
response: any;
}) => {
// do something
}
1.) 请求和响应是明确的“任何”,我尽量避免,因为没有可用的类型安全和代码完成。2.) 我想在类语法中使用可扩展的基控制器来执行此操作,从该控制器派生出其他类。
我搞砸了什么
所以目前我最终得到了这样的东西(这很没有意义):
import type { RouterContext } from "https://deno.land/x/oak@v8.0.0/mod.ts";
export class BaseController {
// deno-lint-ignore no-explicit-any
protected ctx: RouterContext<{ id: string }, Record<string, any>>;
// deno-lint-ignore no-explicit-any
constructor(ctx: RouterContext<{ id: string }, Record<string, any>>) {
this.ctx = this.getContext(ctx);
}
// deno-lint-ignore no-explicit-any
getContext = (ctx: RouterContext<{ id: string }, Record<string, any>>) => {
return ctx;
};
}
正如你所看到的,除了接收一些传递给控制器的上下文之外,这几乎没有任何作用,这没有任何意义,因为
router.get("/", (ctx) => { SomeController.createSomething(ctx) })
我需要在我的路线中做类似的事情。- 我需要到处传递上下文(这显然不是目标)。如果我扩展了一个有
BaseController
自己的构造函数的类,我什至需要在这里传递上下文super(ctx : UltraLongType<ThatIDontWantHere>)
我真正想要达到的目标
长话短说:我真正想做的是BaseController.getContext
真正获取当前上下文,而不是到处传递它。
不幸的是,我找不到一些帮助器或注入器或任何服务来从“外部”接收当前的 RouterContext。
我真的不明白这一点。
也许有人可以帮助我:)
在此先感谢和最好的问候:)
解决方案
推荐阅读
- sql-server - 如果链接服务器关闭 SQL Server 中的查询会发生什么情况?
- swift - 将通用占位符约束到其他通用占位符
- corda - 如何更新保险库中的项目?
- oracle - 基于仪表板提示选择的 BI 答案/视图中的动态列选择
- windows - 如何仅将文件夹中的新文件复制到 Windows 中的另一个文件夹中?
- android - 在 android 10 及更高版本的 Webview 中显示图像的有效方法是什么?
- android - 在 android 中,local-broadcast-receivers 、 event-bus 和 rx-bus 之间的区别
- r - 如何理解 r 中的 maxLik 的结果?
- java - 在 glassfish3 服务器上上传应用程序文件 (ords.war) 时发生部署错误
- transactions - 比特币核心 - 如何在将 BTC 发送到某个地址之前获取交易大小