Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat] 유저 정보 조회 API 구현 #288

Merged
merged 19 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/api/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class AuthController {
this.cookieInsertJWT(response, userId);
}

@Post('guest/login')
@Get('guest/login')
@ApiOperation({ summary: '게스트 로그인' })
@ApiResponse({ status: 302, description: '홈으로 리다이렉션' })
@UseGuards(ThrottlerGuard)
Expand Down
5 changes: 4 additions & 1 deletion apps/api/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,16 @@ export class AuthService {

async createGuestUser() {
const randomNum = Math.floor(Math.random() * 10000);
const response = await fetch('https://api.thecatapi.com/v1/images/search');
const catImageUrl = (await response.json())[0].url;

const guestUser = {
username: `guest_${randomNum}`,
password: `guest_password_${randomNum}`,
email: `[email protected]`,
nickname: `guest_${randomNum}`,
introduce: `게스트 사용자입니다. `,
profileImageUrl: `https://cataas.com/cat?${Date.now()}`,
profileImageUrl: catImageUrl,
};
const user = await this.userService.findUserByUsername(guestUser.username);
if (!user) {
Expand Down
6 changes: 6 additions & 0 deletions apps/api/src/ticle/dto/ticleDetailDto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ export class TickleDetailResponseDto {
})
speakerName: string;

@ApiProperty({
example: 1,
description: '발표자 유저 아이디',
})
speakerId: number;

@ApiProperty({
example: '[email protected]',
description: '발표자 이메일',
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/ticle/ticle.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ export class TicleService {

return {
...ticleData,
speakerId: ticle.speaker.id,
tags: tags.map((tag) => tag.name),
speakerImgUrl: speaker.profileImageUrl,
};
Expand Down
33 changes: 33 additions & 0 deletions apps/api/src/user/dto/userProfileDto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { ApiProperty } from '@nestjs/swagger';

export class UserProfileDto {
@ApiProperty({
example: '1',
description: '유저 아이디',
})
id: number;

@ApiProperty({
example: 'simeunseo',
description: '유저 닉네임',
})
nickname: string;

@ApiProperty({
example: 'https://avatars.githubusercontent.com/u/55528304?v=4',
description: '유저 프로필 사진',
})
profileImageUrl: string;

@ApiProperty({
example: 'github',
description: '유저 소셜 로그인 프로바이더',
})
provider: string;

@ApiProperty({
example: ['개발자를 위한 피그마', '야, 너도 부캠할 수 있어'],
description: '유저가 개설한 티클 목록',
})
ticles: string[];
}
27 changes: 27 additions & 0 deletions apps/api/src/user/dto/userProfileOfMeDto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { ApiProperty } from '@nestjs/swagger';

export class UserProfileOfMeDto {
@ApiProperty({
example: '1',
description: '유저 아이디',
})
id: number;

@ApiProperty({
example: 'simeunseo',
description: '유저 닉네임',
})
nickname: string;

@ApiProperty({
example: 'https://avatars.githubusercontent.com/u/55528304?v=4',
description: '유저 프로필 사진',
})
profileImageUrl: string;

@ApiProperty({
example: 'github',
description: '유저 소셜 로그인 프로바이더',
})
provider: string;
}
22 changes: 16 additions & 6 deletions apps/api/src/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import { Controller, Get, Patch } from '@nestjs/common';
import { Controller, Get, Param, UseGuards } from '@nestjs/common';

import { JwtAuthGuard } from '@/auth/jwt/jwt-auth.guard';
import { GetUserId } from '@/common/decorator/get-userId.decorator';

import { UserService } from './user.service';

@Controller('user')
export class UserController {
constructor() {}
constructor(private readonly userService: UserService) {}

@Get('profile')
getUserProfile() {}
@Get('me')
@UseGuards(JwtAuthGuard)
async getUserProfile(@GetUserId() userId: number) {
return await this.userService.findUserProfileOfMeByUserId(userId);
}

@Patch('profile')
patchUserProfile() {}
@Get(':userId')
async patchUserProfile(@Param('userId') userId: number) {
return await this.userService.findUserProfileByUserId(userId);
}
}
39 changes: 38 additions & 1 deletion apps/api/src/user/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ConflictException, Injectable } from '@nestjs/common';
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
Expand All @@ -8,6 +8,8 @@

import { CreateLocalUserDto } from './dto/createLocalUser.dto';
import { CreateSocialUserDto } from './dto/createSocialUser.dto';
import { UserProfileDto } from './dto/userProfileDto';
import { UserProfileOfMeDto } from './dto/userProfileOfMeDto';

@Injectable()
export class UserService {
Expand All @@ -24,7 +26,7 @@
password: hashedPassword,
});
await this.userRepository.save(user);
const { password, ...result } = user;

Check warning on line 29 in apps/api/src/user/user.service.ts

View workflow job for this annotation

GitHub Actions / check

'password' is assigned a value but never used
return result;
}

Expand Down Expand Up @@ -64,4 +66,39 @@
}
return user;
}

async findUserProfileOfMeByUserId(userId: number): Promise<UserProfileOfMeDto> {
const user = await this.userRepository.findOne({
where: { id: userId },
select: ['id', 'nickname', 'profileImageUrl', 'provider'],
});

if (!user) {
throw new NotFoundException(ErrorMessage.USER_NOT_FOUND);
}

return user;
}

async findUserProfileByUserId(userId: number): Promise<UserProfileDto> {
const user = await this.userRepository
.createQueryBuilder('user')
.leftJoin('user.ticles', 'ticles')
.addSelect('ticles.title')
.where('user.id = :userId', { userId: userId })
.getOne();
Comment on lines +84 to +89
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q:
TypeORMfind({relations})와 동일한 결과 값을 반환할 것 같은데 queryBuilder를 사용하신 이유가 있을까요?


if (!user) {
throw new NotFoundException(ErrorMessage.USER_NOT_FOUND);
}

const ticles = user.ticles || [];
return {
id: user.id,
nickname: user.nickname,
profileImageUrl: user.profileImageUrl,
provider: user.provider,
ticles: ticles.map((ticle) => ticle.title),
};
Comment on lines +96 to +102
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

p5:
만약 QueryBuilder를 사용하는게 목적이라면 QueryBuilder를 통해 직접 조회하는 것도 좋을 것 같습니다! (학습 목적으로)

}
}
8 changes: 6 additions & 2 deletions apps/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@
<html lang="ko">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/svg+xml" href="/favicon.png" />
<link
rel="stylesheet"
as="style"
crossorigin
href="https://cdn.jsdelivr.net/gh/orioncactus/[email protected]/dist/web/static/pretendard-dynamic-subset.min.css"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ticle</title>
<meta
name="Description"
content="작은 지식이 모여 큰 성장이 되는 곳 - 실시간 지식 공유 플랫폼 TICLE"
/>
<title>TICLE</title>
</head>
<body>
<div id="root"></div>
Expand Down
Binary file added apps/web/public/favicon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 8 additions & 3 deletions apps/web/src/api/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import axiosInstance from '@/api/axios';
import { ENV } from '@/constants/env';

type SignUpDto = {
username: string;
Expand All @@ -23,8 +24,12 @@ const signOut = async () => {
await axiosInstance.post('/auth/logout');
};

const oauthLogin = async (provider: 'google' | 'github') => {
await axiosInstance.get(`/auth/${provider}/login`);
const guestLogin = () => {
window.location.href = `${ENV.API_URL}/auth/guest/login`;
};

export { logIn, signUp, oauthLogin, signOut };
const oauthLogin = (provider: 'google' | 'github') => {
window.location.href = `${ENV.API_URL}/auth/${provider}/login`;
};

export { logIn, signUp, oauthLogin, guestLogin, signOut };
4 changes: 2 additions & 2 deletions apps/web/src/assets/icons/chevron-right.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 17 additions & 0 deletions apps/web/src/assets/icons/github.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions apps/web/src/assets/icons/google.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion apps/web/src/assets/ticle.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading