import { Inject , OnModuleInit , UseGuards } from '@nestjs/common' ; import { ClientGrpcProxy } from '@nestjs/microservices' ; import { Resolver , Args , Mutation } from '@nestjs/graphql' ; import { PinoLogger } from 'nestjs-pino' ; import { IUsersService } from './users.interface' ; import { User , UserPayload , UpdateProfileInput , UpdateEmailInput , UpdatePasswordInput , DeleteAccountPayload } from '../graphql/typings' ; import { PasswordUtils } from '../utils/password.utils' ; import { GqlAuthGuard } from '../auth/gql-auth.guard' ; import { CurrentUser } from '../auth/user.decorator' ; @ Resolver ( ) export class UsersMutationResolver implements OnModuleInit { constructor ( @ Inject ( 'UsersServiceClient' ) private readonly usersServiceClient , private readonly passwordUtils , private readonly logger ) { logger . setContext ( UsersMutationResolver . name ) ; } private usersService : IUsersService ; onModuleInit ( ) { this . usersService = this . usersServiceClient . getService < IUsersService > ( 'UsersService' ) ; } @ Mutation ( ) @ UseGuards ( GqlAuthGuard ) async updateProfile ( @ CurrentUser ( ) user , @ Args ( 'data' ) data ) { const updatedUser = await this . usersService . update ( { id : user . id , data : { ... data } } ) . toPromise ( ) ; return { user : updatedUser } ; } @ Mutation ( ) @ UseGuards ( GqlAuthGuard ) async updateEmail ( @ CurrentUser ( ) user , @ Args ( 'data' ) data ) { const { count } = await this . usersService . count ( { where : JSON . stringify ( { email : data . email } ) } ) . toPromise ( ) ; if ( count >= 1 ) throw new Error ( 'Email taken' ) ; const isSame = await this . passwordUtils . compare ( data . currentPassword , user . password ) ; if ( ! isSame ) throw new Error ( 'Error updating email. Kindly check the email or password provided' ) ; const updatedUser = await this . usersService . update ( { id : user . id , data : { ... data } } ) . toPromise ( ) ; return { user : updatedUser } ; } @ Mutation ( ) @ UseGuards ( GqlAuthGuard ) async updatePassword ( @ CurrentUser ( ) user , @ Args ( 'data' ) data ) { const isSame = await this . passwordUtils . compare ( data . currentPassword , user . password ) ; const isConfirmed = data . newPassword === data . confirmPassword ; if ( ! isSame || ! isConfirmed ) { throw new Error ( 'Error updating password. Kindly check your passwords.' ) ; } const password = await this . passwordUtils . hash ( data . newPassword ) ; const updatedUser = await this . usersService . update ( { id : user . id , data : { password } } ) ; return { user : updatedUser } ; } @ Mutation ( ) @ UseGuards ( GqlAuthGuard ) async deleteAccount ( @ CurrentUser ( ) user ) { return this . usersService . destroy ( { where : JSON . stringify ( { id : user . id } ) } ) . toPromise ( ) ; } }