简体   繁体   中英

Nestjs - Inject Data In Decorator

class CreateAssetDto{
  assetName: string;
  tenant: Tenant;
}

export const InjectTenant = createParamDecorator(
    (data: string, ctx: ExecutionContext) => {
      const request = ctx.switchToHttp().getRequest();
      let createAssetDto = new CreateAssetDto();
      createAssetDto.tenant = new Tenant("JAY")
      return createAssetDto;
    }

);

async create(@InjectTenant() createAssetDto: CreateAssetDto) {
    console.log(createAssetDto.tenant);

Hi, how to inject data using decorator parameter. for example everytime I call create function. it automatically inject tenant property.

when I tried it. it never call @InjectTenant decorator

You can Inject it in the request so that you can get the object wherever you want to... Take a look at the following code

export const InjectTenant = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
  const request = ctx.switchToHttp().getRequest(); 
  let createAssetDto = new CreateAssetDto();
  createAssetDto.assetName = "CAR"
  request.createAssetDto = createAssetDto;
  return request;
}
);

now in your controller, you can access it via Req() method

@InjectTenant()
@Post('/Your-Route')
async create(@Body() createAssetDto: CreateAssetDto, @Req() req:any ) {
console.log(req.createAssetDto);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM