|
1 |
| -import { BadRequestException, Injectable, Logger } from '@nestjs/common'; |
| 1 | +import { BadRequestException, ConflictException, Injectable, Logger } from '@nestjs/common'; |
2 | 2 | import { AppError } from '../../core/enums/app-error.enum';
|
3 | 3 | import { LanguageService } from '../../core/services/language.service';
|
4 | 4 | import { UserRepository } from './user.repository';
|
5 | 5 | import { GetMeResponse } from './dto/get-me.response';
|
6 | 6 | import { User } from '@prisma/client';
|
7 | 7 | import { UpdateUserResponse } from './dto/update-user.response';
|
8 | 8 | import { UpdateUserRequest } from './dto/update-user.request';
|
| 9 | +import { CatchPokemonRequest } from './dto/catch-pokemon.request'; |
9 | 10 |
|
10 | 11 | @Injectable()
|
11 | 12 | export class UserService {
|
@@ -64,4 +65,56 @@ export class UserService {
|
64 | 65 | });
|
65 | 66 | }
|
66 | 67 | }
|
| 68 | + |
| 69 | + async catchPokemon( |
| 70 | + userId: string, |
| 71 | + catchPokemonRequest: CatchPokemonRequest, |
| 72 | + ): Promise<UpdateUserResponse> { |
| 73 | + if (!userId) { |
| 74 | + throw new BadRequestException({ |
| 75 | + code: AppError.USER_NOT_FOUND, |
| 76 | + message: `User not found`, |
| 77 | + }); |
| 78 | + } |
| 79 | + |
| 80 | + const userWithoutPokemon = await this.userRepository.getUserById(userId); |
| 81 | + if (!userWithoutPokemon) { |
| 82 | + throw new BadRequestException({ |
| 83 | + code: AppError.USER_NOT_FOUND, |
| 84 | + message: `User with id ${userId} not found`, |
| 85 | + }); |
| 86 | + } |
| 87 | + |
| 88 | + return this.addPokemonToUser({ userId, userWithoutPokemon, catchPokemonRequest }); |
| 89 | + } |
| 90 | + |
| 91 | + private async addPokemonToUser(data: { |
| 92 | + userId: string; |
| 93 | + userWithoutPokemon: Omit<User, 'password'>; |
| 94 | + catchPokemonRequest: CatchPokemonRequest; |
| 95 | + }) { |
| 96 | + const pokemonsCaught = data.userWithoutPokemon.caughtPokemonIds; |
| 97 | + const { pokemonId } = data.catchPokemonRequest; |
| 98 | + if (pokemonsCaught.includes(pokemonId)) { |
| 99 | + throw new ConflictException({ |
| 100 | + code: AppError.POKEMON_ALREADY_CAUGHT, |
| 101 | + message: `You already have caught pokemon with id: ${pokemonId}`, |
| 102 | + }); |
| 103 | + } |
| 104 | + pokemonsCaught.push(pokemonId); |
| 105 | + |
| 106 | + try { |
| 107 | + const userUpdated = await this.userRepository.updateUserById(data.userId, { |
| 108 | + ...data.userWithoutPokemon, |
| 109 | + caughtPokemonIds: pokemonsCaught, |
| 110 | + }); |
| 111 | + this.logger.log(`[CatchPokemon]: user updated successfully`); |
| 112 | + return { user: userUpdated }; |
| 113 | + } catch { |
| 114 | + throw new BadRequestException({ |
| 115 | + code: AppError.UPDATE_USER_FAILED, |
| 116 | + message: `Unable to update user`, |
| 117 | + }); |
| 118 | + } |
| 119 | + } |
67 | 120 | }
|
0 commit comments