在nest.js中,是否可以在参数装饰器中获取服务实例?

时间:2019-04-07 15:50:34

标签: javascript node.js typescript decorator nestjs

我想使用nest.js实现类似的功能: (与Spring框架非常相似)

@Controller('/test')
class TestController {
  @Get()
  get(@Principal() principal: Principal) {

  }
}

阅读文档数小时后,我发现nest.js支持创建自定义装饰器。因此,我决定实现自己的@Principal装饰器。装饰者负责从http标头中检索访问令牌,并使用该令牌从我自己的身份验证服务中获取用户主体。

import { createParamDecorator } from '@nestjs/common';

export const Principal = createParamDecorator((data: string, req) => {
  const bearerToken = req.header.Authorization;
  // parse.. and call my authService..
  // how to call my authService here?
  return null;
});

但是问题是我不知道如何在装饰处理程序中获取服务实例。可能吗?如何?预先谢谢你

3 个答案:

答案 0 :(得分:3)

无法将服务注入到您的自定义装饰器中。

相反,您可以创建有权访问您的服务的AuthGuard。然后,防护人员可以将属性添加到request对象,然后可以使用自定义装饰器访问该属性:

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const bearerToken = req.header.Authorization;
    const user = await this.authService.authenticate(bearerToken);
    request.principal = user;
    // If you want to allow the request even if auth fails, always return true
    return !!user;
  }
}
import { createParamDecorator } from '@nestjs/common';

export const Principal = createParamDecorator((data: string, req) => {
  return req.principal;
});

,然后在您的控制器中:

@Get()
@UseGuards(AuthGuard)
get(@Principal() principal: Principal) {
  // ...
}

请注意,nest提供了一些用于身份验证的标准模块,请参见docs

答案 1 :(得分:1)

您可以对所有控制器使用中间件。

auth.middleware.ts


interface AccountData {
  accId: string;
  iat: number;
  exp: number;
}

interface RequestWithAccountId extends Request {
  accId: string;
}

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  constructor(private readonly authenticationService: AuthenticationService) {}
  async use(req: RequestWithAccountId, res: Response, next: NextFunction) {
    const token =
      req.body.token || req.query.token || req.headers['authorization'];
    if (!token) {
      throw new UnauthorizedException();
    }
    try {
      const {
        accId,
      }: AccountData = await this.authenticationService.verifyToken(token);
      req.accId = accId;
      next();
    } catch (err) {
      throw new UnauthorizedException();
    }
  }
}

然后创建 AccountId 装饰器

account-id.decorator.ts

import {
  createParamDecorator,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';

export const AccountId = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const req = ctx.switchToHttp().getRequest();
    const token = req.accId;
    if (!token) {
      throw new UnauthorizedException();
    }
    return token;
  },
);

然后在控制器中应用 AccountId 装饰器

your.controller.ts

  @Get()
  async someEndpoint(
    @AccountId() accountId,
  ) {
    console.log('accountId',accontId)
  }

答案 2 :(得分:0)

对于 NestJS v7

创建自定义管道

// parse-token.pipe.ts
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
import { AuthService } from './auth.service';

@Injectable()
export class ParseTokenPipe implements PipeTransform {
    // inject any dependency
    constructor(private authService: AuthService) {}
    
    async transform(value: any, metadata: ArgumentMetadata) {
        console.log('additional options', metadata.data);
        return this.authService.parse(value);
    }
}

将此管道与属性装饰器一起使用

// decorators.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { ParseTokenPipe} from './parse-token.pipe';

export const GetToken = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
  return ctx.switchToHttp().getRequest().header.Authorization;
});

export const Principal = (additionalOptions?: any) => GetToken(additionalOptions, ParseTokenPipe);

在有或没有附加选项的情况下使用这个装饰器

@Controller('/test')
class TestController {
  @Get()
  get(@Principal({hello: "world"}) principal) {}
}