[英]How to properly use Observables with nestjs?
我正在研究一个 API,它可以处理用户(为了简单起见)做基本的 crud 操作。 我得到了类似的用户服务:
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) { }
...
async findById(id: number): Promise<User> {
return this.usersRepository.findOne(id);
}
和 controller:
@UseGuards(JwtAuthGuard)
@UseInterceptors(ClassSerializerInterceptor)
@UseFilters(QueryFailedExceptionFilter)
@Controller('users')
export class UsersController {
constructor(private readonly _userService: UsersService) { }
@Get(':id')
findById(@Param('id', ParseIntPipe) id: number): Observable<User> {
return from(this._userService.findById(id));
}
这很有效,我可以找到、创建、删除等。问题是,如果我尝试 finOne 用户(我的 controller 中的 Get(:id) ),如果它不存在,它只会返回 200 ok 而没有响应到客户端,但它应该是 404,因为找不到资源。
阅读我理解的文档(希望我做对了),我们可以返回一个 observable 并且它会被自动订阅。 所以问题是,如果 findOne 的结果是空的,在哪里以及如何处理,并返回一个具有适当状态的响应,当然使用 observables。
我试图找到一些例子,但我只找到了几个使用 promises 的例子,而且大多数时候他们只是忽略了 not find 用户案例。
PD:“他们”说我应该在 controller 中处理这个问题
如果你想返回 404 并使用 observables,你可以这样做:
@UseGuards(JwtAuthGuard)
@UseInterceptors(ClassSerializerInterceptor)
@UseFilters(QueryFailedExceptionFilter)
@Controller('users')
export class UsersController {
constructor(private readonly _userService: UsersService) { }
@Get(':id')
findById(@Param('id', ParseIntPipe) id: number): Observable<User> {
return from(this._userService.findById(id)).pipe(
map(user => {
if (!user) {
throw new NotFoundException();
}
return user;
})
);
}
我个人很喜欢将我的所有逻辑都保留在服务中而不是控制器中,从而使控制器保持纤薄,并且大部分逻辑可重用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.