I'm struggling with the following scenario using Deno with Oak.
Most tutorials use export const xy = () => {}
syntax, when they separate controllers and routes.
In the route then they commonly have something like router.get("/the-route", xy)
, which is fine, but has several caveats that I want to avoid.
What I don't want
Look at this example:
const someController = async ({
request,
response,
}: {
request: any;
response: any;
}) => {
// do something
}
1.) request and response are explicitly "any", which I try to avoid since there is no typesafty and no code-completion availabe. 2.) I want to do this in a class-syntax with an extendable base-controller from which other classes are derived.
What I messed up
So currently I ended up with something like this (which is pretty senseless):
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;
};
}
As you can see this does pretty much nothing but receiving some context passed down to the controller, which doesn't make any sense, since
- I need to do something like
router.get("/", (ctx) => { SomeController.createSomething(ctx) })
in my routes. - I need to pass the context everywhere (which clearly is not the goal). If I extended a class with
BaseController
that has a constructor on it's own I even need to pass the context here withsuper(ctx : UltraLongType<ThatIDontWantHere>)
What I really want to achieve
Long story short: What I really want to do is to have BaseController.getContext
really GET the current context without passing it everywhere.
I unfortunately can't find some helper or injector or whatever service to receive the current RouterContext from "outside".
And I really don't get my head wrapped around this.
Maybe someone can help me with this :)
Thanks in advance and best regards :)