装饰器在Nest控制器中返回404 [英] Decorator to return a 404 in a Nest controller

查看:594
本文介绍了装饰器在Nest控制器中返回404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NestJS开发后端(顺便说一下).我有一个获取实体情况的单个实例的标准",类似于下面的示例.

I'm working on a backend using NestJS, (which is amazing btw). I have a 'standard get a single instance of an entity situation' similar to this example below.

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

这非常简单并且有效-但是,如果用户不存在,服务将返回未定义的状态,并且控制器将返回200状态代码和空响应.

This is incredibly simple and works - however, if the user does not exist, the service returns undefined and the controller returns a 200 status code and an empty response.

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

In order to make the controller return a 404, I came up with the following:

    @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();
        }
    }
    ..
    ..

这行得通,但是代码更多(可以重构).

This works, but is a lot more code-y (yes it can be refactored).

这实际上可以使用装饰器来处理这种情况:

This could really use a decorator to handle this situation:

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

有没有人知道这样做的装饰器,还是比上述装饰器更好的解决方案?

Anyone aware of a decorator that does this, or a better solution than the one above?

推荐答案

最简单的方法是

@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;
}

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

There is no point in decorator here because it would have the same code.

注意::BadRequestException是从@nestjs/common导入的;

修改

经过一段时间,我提出了另一种解决方案,它是DTO中的装饰器:

After some time with, I came with another solution, which is a decorator in the 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;
}

希望它对某人有帮助.

这篇关于装饰器在Nest控制器中返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆