Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJs - How to get url of handler?

Tags:

nestjs

I want to redirect user to another url in my server, but I do not want to hardcode url like res.redirect('/hello_world'). Instead I want to just specify handler's url of specified controller like res.redirect(HelloWorldController.handlerName.url) where HelloWorldContoller is

@Controller()
export class HelloWorldController {
    @Get('hello_world')
    handlerName(): string {
        return 'Hello World!';
    }
}
like image 411
Nursultan Zarlyk Avatar asked Apr 20 '18 05:04

Nursultan Zarlyk


People also ask

How do I get parameters in Nestjs?

To get all query parameter values from a GET request, you can use the @Query() decorator function from the @nestjs/common module inside the parameter brackets of the controller's respective method in Nestjs.

How do I get headers in Nestjs?

How do I get headers in Nestjs? Headers. To specify a custom response header, you can either use a @Header() decorator or a library-specific response object (and call res. header() directly).

How do I get my Nestjs HTTP status code?

To return a status code in nestjs, you need to include the @Res() in your parameters. Normally in nestjs the passthrough option on the Response object is set to false by default.

What is DTO in Nestjs?

A DTO is an object that defines how the data will be sent over the network. We could determine the DTO schema by using TypeScript interfaces, or by simple classes. Interestingly, we recommend using classes here.


1 Answers

For example, you can use Reflect to get metadata like this:

import { PATH_METADATA } from '@nestjs/common/constants';

@Controller('api')
export class ApiController {
  @Get('hello')
  root() {
    let routePath = Reflect.getMetadata(PATH_METADATA, StaticController);
    routePath += '/' + Reflect.getMetadata(PATH_METADATA, StaticController.prototype.serveStatic);
    console.log(routePath); will return `api/hello`
    return {
      message: 'Hello World!',
    };
  }
}
  1. We get api metadata
  2. Then it's methods

Why it returns api/hello if I need a path not of self url, but other controller's url?

Here StaticController is used as an example, You can import any other controllers and pass it to Reflect.getMetadata(PATH_METADATA, AnyOtherController);

like image 87
Yerkon Avatar answered Oct 19 '22 02:10

Yerkon