简体   繁体   中英

How to properly use Observables with nestjs?

Im working on a API that can hanlde users (just that for simplicity) doing basic crud operations. 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:

@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.

Reading the documentation i understand (hope i did it right) that we can return a observable and it will be automatically subcribed. 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.

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.

PD: "They" said that i should hanlde that in the controller

If you want to return a 404 and use observables, what you can do is something like this:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM