首页 > 解决方案 > 使用 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;
  };
}

正如你所看到的,除了接收一些传递给控制器​​的上下文之外,这几乎没有任何作用,这没有任何意义,因为

  1. router.get("/", (ctx) => { SomeController.createSomething(ctx) })我需要在我的路线中做类似的事情。
  2. 我需要到处传递上下文(这显然不是目标)。如果我扩展了一个有BaseController自己的构造函数的类,我什至需要在这里传递上下文super(ctx : UltraLongType<ThatIDontWantHere>)

我真正想要达到的目标

长话短说:我真正想做的是BaseController.getContext真正获取当前上下文,而不是到处传递它。

不幸的是,我找不到一些帮助器或注入器或任何服务来从“外部”接收当前的 RouterContext。

我真的不明白这一点。

也许有人可以帮助我:)

在此先感谢和最好的问候:)

标签: typescriptdenooak

解决方案


推荐阅读