본문 바로가기

Uber Eats

Uber Eats # 18 User Profile

sync와 async의 차이를 알아야 userProfile 쿼리 작성 시 생기는 에러를 해결할 수 있다. 

 

@UseGuards(AuthGuard)
    @Query(returns => UserProfileOutput)
    userProfile(@Args() userProfileInput: UserProfileInput): Promise<UserProfileOutput> {
        try{
            const user = this.usersService.findById(userProfileInput.userId);
        } catch (e) {
            return {
              error: 'User Not Found',
              ok: false,
            };
        }
    }


// 에러
src/users/users.resolver.ts:60:15 - error TS2322: Type '{ error: string; ok: boolean; }' is not assignable to type 'Promise<UserProfileOutput>'.
  Object literal may only specify known properties, and 'error' does not exist in type 'Promise<UserProfileOutput>'.

60               error: 'User Not Found',

리턴값을 보면 Promise<UserProfileOutput>이다. Promise는 자바스크립트 비동기 처리를 위한 객체이다. 비동기 처리를 하기 위해 콜백함수를 활용하거나 async, await를 사용해서 처리할 수 있다. 

따라서 위의 에러는 비동기 처리를 하지 않았기 때문에 발생한 에러였다. 

아래는 비동기 처리를 한 코드이다.

 

@UseGuards(AuthGuard)
    @Query(returns => UserProfileOutput)
    async userProfile(@Args() userProfileInput: UserProfileInput): Promise<UserProfileOutput> {
        try{
           const user = await this.usersService.findById(userProfileInput.userId);
        } catch (e) {
            return {
              error: 'User Not Found',
              ok: false,
            };
        }
    }

typeorm이 update 하기 전에 @BeforeUpdate()를 사용하여 password를 해쉬 하려고 했지만 작동하지 않았다. 그 이유는 users repository에서 update를 사용하고 있다. 설명에 보면 entity가 있는지 없는지 확인하지 않고 db에 query만 보낸다. 그래서 BeforeUpdate를 부르지 않는다. 즉, 특정 entity를 업데이트 해야지만 @BeforeUpdate를 부르는 것이다. 그래서 this.users.update를 하지 않고 save를 사용한다. 

 

@UseGuards(AuthGuard)
    @Mutation(returns => EditProfileOutput)
    async editProfile(
        @AuthUser() authUser: User,
        @Args('input') editProfileInput: EditProfileInput,
    ): Promise<EditProfileOutput> {
        try {
            await this.usersService.editProfile(authUser.id, editProfileInput);
            return {
                ok: true
            }
        } catch (error) {
            return {
                ok: false,
                error,
            };
        }
    }