import { BadRequestException , Component , ConflictException , InternalServerErrorException , NotFoundException } from "@nestjs/common" ; import { InjectRepository } from "@nestjs/typeorm" ; import { Repository } from "typeorm" ; import { Client , User } from "./models" ; import { DbErrorCode } from "../enums/db-error-code.enum" ; @ Component ( ) export class OAuthService { constructor ( @ InjectRepository ( Client ) private readonly clientsRepository , @ InjectRepository ( User ) private readonly usersRepository ) { } async createClient ( client ) { try { let c = await this . clientsRepository . save ( client ) ; return Promise . resolve ( c ) ; } catch ( e ) { if ( e . code ) { if ( DbErrorCode . UNIQUE_VIOLATION == e . code ) { throw new BadRequestException ( "Sorry, already exists an client registered with the same name." ) ; } else if ( DbErrorCode . NOT_NULL_VIOLATION == e . code || DbErrorCode . CHECK_VIOLATION == e . code || DbErrorCode . STRING_DATA_RIGHT_TRUNCATION == e . code ) { throw new BadRequestException ( "Unable to create the client due to invalid client data." ) ; } } throw new InternalServerErrorException ( "An unexpected error has occurred trying to create the client." ) ; } } async getClientById ( id ) { let client = await this . clientsRepository . findOneById ( id ) ; if ( ! client ) { throw new NotFoundException ( "The client was not found" ) ; } return client ; } async updateClient ( client ) { let updatedClient = await this . clientsRepository . save ( client ) ; if ( ! updatedClient ) { throw new NotFoundException ( "The client was not found" ) ; } return updatedClient ; } async createUser ( user ) { try { let u = await this . usersRepository . save ( user ) ; return Promise . resolve ( u ) ; } catch ( e ) { console . log ( e ) ; if ( e . code ) { if ( DbErrorCode . UNIQUE_VIOLATION == e . code ) { throw new BadRequestException ( "Sorry, already exists an user registered with the same name." ) ; } else if ( DbErrorCode . NOT_NULL_VIOLATION == e . code || DbErrorCode . CHECK_VIOLATION == e . code || DbErrorCode . STRING_DATA_RIGHT_TRUNCATION == e . code ) { console . log ( e . code ) ; throw new BadRequestException ( "Unable to create the user due to invalid user data." ) ; } } throw new InternalServerErrorException ( "An unexpected error has occurred trying to create the user." ) ; } } async getUserById ( id ) { let user = await this . usersRepository . findOneById ( id ) ; if ( ! user ) { throw new NotFoundException ( "The user was not found" ) ; } return user ; } async updateUser ( user ) { let updatedUser = await this . usersRepository . save ( user ) ; if ( ! updatedUser ) { throw new ConflictException ( "Unable to update the user" ) ; } return updatedUser ; } }