Decorator在Nest控制器中返回404

问题描述 投票:5回答:2

我正在使用NestJS开发后端(这真是太棒了)。我有一个'标准获取实体情况的单一实例',类似于下面这个例子。

@Controller('user')
export class UserController {
    constructor(private readonly userService: UserService) {}
    ..
    ..
    ..
    @Get(':id')
    async findOneById(@Param() params): Promise<User> {
        return userService.findOneById(params.id);
    }

这非常简单且有效 - 但是,如果用户不存在,则服务返回undefined,控制器返回200状态代码和空响应。

为了让控制器返回404,我想出了以下内容:

    @Get(':id')
    async findOneById(@Res() res, @Param() params): Promise<User> {
        const user: User = await this.userService.findOneById(params.id);
        if (user === undefined) {
            res.status(HttpStatus.NOT_FOUND).send();
        }
        else {
            res.status(HttpStatus.OK).json(user).send();
        }
    }
    ..
    ..

这是有效的,但代码更多(是的,它可以重构)。

这可能真的使用装饰器来处理这种情况:

    @Get(':id')
    @OnUndefined(404)
    async findOneById(@Param() params): Promise<User> {
        return userService.findOneById(params.id);
    }

任何人都知道这样做的装饰者,或者比上面的解决方案更好的解决方案?

javascript node.js nestjs
2个回答
6
投票

最简单的方法是

@Get(':id')
async findOneById(@Param() params): Promise<User> {
    const user: User = await this.userService.findOneById(params.id);
    if (user === undefined) {
        throw new BadRequestException('Invalid user');
    }
    return user;
}

这里的装饰器没有任何意义,因为它具有相同的代码。

注意:BadRequestException是从@nestjs/common进口的;

编辑

经过一段时间,我带来了另一个解决方案,它是DTO中的装饰者:

import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint } from 'class-validator';
import { createQueryBuilder } from 'typeorm';

@ValidatorConstraint({ async: true })
export class IsValidIdConstraint {

    validate(id: number, args: ValidationArguments) {
        const tableName = args.constraints[0];
        return createQueryBuilder(tableName)
            .where({ id })
            .getOne()
            .then(record => {
                return record ? true : false;
            });
    }
}

export function IsValidId(tableName: string, validationOptions?: ValidationOptions) {
    return (object, propertyName: string) => {
        registerDecorator({
            target: object.constructor,
            propertyName,
            options: validationOptions,
            constraints: [tableName],
            validator: IsValidIdConstraint,
        });
    };
}

然后在你的DTO中:

export class GetUserParams {
    @IsValidId('user', { message: 'Invalid User' })
    id: number;
}

希望它可以帮助某人。


3
投票

没有内置的装饰器,但你可以创建一个interceptor来检查返回值并在NotFoundException上抛出undefined

拦截器

@Injectable()
export class NotFoundInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {
    // stream$ is an Observable of the controller's result value
    return stream$
      .pipe(tap(data => {
        if (data === undefined) throw new NotFoundException();
      }));
  }
}

然后,您可以通过将Interceptor添加到单个端点来使用它:

@Get(':id')
@UseInterceptors(NotFoundInterceptor)
findUserById(@Param() params): Promise<User> {
    return this.userService.findOneById(params.id);
}

或者你的Controller的所有端点:

@Controller('user')
@UseInterceptors(NotFoundInterceptor)
export class UserController {

动态拦截器

您还可以将值传递给拦截器以自定义每个端点的行为。

传递构造函数中的参数:

@Injectable()
export class NotFoundInterceptor implements NestInterceptor {
  constructor(private errorMessage: string) {}
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {
    return stream$
      .pipe(tap(data => {
        if (data === undefined) throw new NotFoundException(this.errorMessage);
                                                            ^^^^^^^^^^^^^^^^^
      }));
  }
}

然后使用new创建拦截器:

@Get(':id')
@UseInterceptors(new NotFoundInterceptor('No user found for given userId'))
findUserById(@Param() params): Promise<User> {
    return this.userService.findOneById(params.id);
}
© www.soinside.com 2019 - 2024. All rights reserved.