-
import {UseAfter} from "@tsed/platform-middlewares";
import {useDecorators} from "@tsed/core";
export function CustomStatus(code: number) {
return useDecorators(
UseAfter((req: any, res: any, next: any) => {
res.status(code);
next();
})
);
} I've seen this example on the docs. How can I use the DI in this case? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 17 replies
-
Use a middleware on class and/or endpoint and store dataThis example show you, how you can create a custom decorator to collect metadata on class and/or on class method and register a middleware. import {Context, Middleware, MiddlewareMethods, UseBeforeEach} from "@tsed/common";
import {StoreSet, useDecorators} from "@tsed/core";
interface MyMiddlewareParams {
code: number;
}
@Middleware()
class MyMiddlewareImpl implements MiddlewareMethods {
static params: MyMiddlewareParams;
async use(@Context() ctx: Context) {
const code = ctx.endpoint.store.get("code") || ctx.endpoint.parent.store.get("code");
ctx.set("code", code);
}
}
export function MyMiddleware(code: number) {
return useDecorators(StoreSet("code", code), UseBeforeEach(MyMiddlewareImpl));
}
Usage on controllerimport {Controller} from "@tsed/di";
import {Get} from "@tsed/schema";
import {Context} from "@tsed/common";
import {MyMiddleware} from "../../middlewares/MyMiddleware";
@Controller("/test")
@MyMiddleware(999) // by default
export class HelloWorldController {
@Get("/scenario-1")
@MyMiddleware(777) // specific to the current endpoint
work(@Context("code") code: number) {
return {code}; // 777
}
@Get("/scenario-2")
doesntWork(@Context("code") code: number) {
return {code}; // 999 - value set on controller
}
} See you |
Beta Was this translation helpful? Give feedback.
Use a middleware on class and/or endpoint and store data
This example show you, how you can create a custom decorator to collect metadata on class and/or on class method and register a middleware.