들어가기
user의 프로필을 확인하는 Query.
dto, resolver, service 순서를 기억한다.
import { ArgsType, Field, ObjectType } from '@nestjs/graphql';
import { MutationOutput } from 'src/common/dtos/output.dto';
import { User } from '../entities/user.entity';
@ArgsType() ///input에 userId만 들어가면 되니, Arg Type으로 해 준다.
export class UserProfileInput {
@Field(() => Number)
userId: number;
}
@ObjectType()
export class UserProfileOutput extends MutationOutput {
@Field(() => User, { nullable: true })
user?: User;
}
///Output부분은 MutationOutput을 extends한 다음에, 추가로 User를 return받게 한다.
nullable:true는 없는id로 인해 user가 return되지 못할떄를 대비한것이다.
async findById(id: number): Promise<User> {
return this.users.findOneBy({ id });
}
///별거 없이 Id를 받아서 user를 return해 주는 함수!!
@UseGuards(AuthGuard) ///다른 사람의 profile이나, 본인 profile을 보기
///위해서는 login된 상태여야함.
@Query(() => UserProfileOutput)
async userProfile(
@Args() userProfileInput: UserProfileInput,
): Promise<UserProfileOutput> {
///dto에서 Arg 타입으로 만들어 주었고, dto의 input, output을 그대로 넣어줌
try {
const user = await this.usersService.findById(userProfileInput.userId);
///dto에서 만든 userProfileInput.userId를 통해서 user찾음.
///servicer에서는 userProfileInpput.userId를 ({id})로 받는거 체크!!
if (!user) {
throw Error(); ///user가 없을시, 밑에 있는 'User not found'에러를
///던져라는 뜻.
}
return {
ok: true,
user, ///찾은 User를 return해 줌!!
};
} catch (e) {
return {
error: 'User not found',
ok: false,
};
}
}