[英]How to properly use Observables with nestjs?
Im working on a API that can hanlde users (just that for simplicity) doing basic crud operations.我正在研究一个 API,它可以处理用户(为了简单起见)做基本的 crud 操作。 I got the user service something like:我得到了类似的用户服务:
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) { }
...
async findById(id: number): Promise<User> {
return this.usersRepository.findOne(id);
}
and a controller:和 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));
}
And that works, i can find, create, delete, etc.. the problem is that if i try to finOne user ( Get(:id) from my controller ) and if it not exist, it just return a 200 ok with no response to the client, but it should be a 404 because the resource is not found.这很有效,我可以找到、创建、删除等。问题是,如果我尝试 finOne 用户(我的 controller 中的 Get(:id) ),如果它不存在,它只会返回 200 ok 而没有响应到客户端,但它应该是 404,因为找不到资源。
Reading the documentation i understand (hope i did it right) that we can return a observable and it will be automatically subcribed.阅读我理解的文档(希望我做对了),我们可以返回一个 observable 并且它会被自动订阅。 So the question is, where and how to hanlde if the result for findOne is nothing and return a response with the appropiate status, using observables of course.所以问题是,如果 findOne 的结果是空的,在哪里以及如何处理,并返回一个具有适当状态的响应,当然使用 observables。
I have try to find some examples, but i only find a few examples working with promises and most of the time they just ignore the not find user case.我试图找到一些例子,但我只找到了几个使用 promises 的例子,而且大多数时候他们只是忽略了 not find 用户案例。
PD: "They" said that i should hanlde that in the controller PD:“他们”说我应该在 controller 中处理这个问题
If you want to return a 404 and use observables, what you can do is something like this:如果你想返回 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;
})
);
}
I'm personally a fan of keeping all of my logic in services instead of controllers, keeps the controllers thin and the logic re-usable for the most part.我个人很喜欢将我的所有逻辑都保留在服务中而不是控制器中,从而使控制器保持纤薄,并且大部分逻辑可重用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.