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

[GWL-176] Profile API를 구현한다. #204

Merged
merged 9 commits into from
Dec 3, 2023
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
1 change: 1 addition & 0 deletions BackEnd/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ <h1>We-Tri: 트라이 애슬론을 우리와 함께해요</h1>
>Download Week 2 App</a
>
<a href="itms-services://?action=download-manifest&amp;url=https://kr.object.ncloudstorage.com/wetri-ios-ipa/iOSweek3/manifest.plist" class="download-button week-3">Download Week 3 App</a>
<a href="itms-services://?action=download-manifest&amp;url=https://kr.object.ncloudstorage.com/wetri-ios-ipa/iOSweek4/manifest.plist" class="download-button week-4">Download Week 4 App</a>
Copy link
Member

Choose a reason for hiding this comment

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

</section>
</main>
<footer>
Expand Down
6 changes: 4 additions & 2 deletions BackEnd/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ export class AuthService {
}

async registerWithUserIdAndProvider(signupInfo: SignupDto) {
if (await this.profilesService.existByNickname(signupInfo.nickname)) {
if (
await this.profilesService.validateProfileNickname(signupInfo.nickname)
) {
throw new NicknameDuplicateException();
}
const newUser = await this.usersService.createUser(signupInfo);
Expand Down Expand Up @@ -81,7 +83,7 @@ export class AuthService {
return false;
}

const profile = await this.profilesService.findByPublicId(decoded.sub);
const profile = await this.profilesService.getProfile(decoded.sub);

if (!profile) {
return false;
Expand Down
1 change: 1 addition & 0 deletions BackEnd/src/auth/dto/signup.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class ProfileDto extends PickType(Profile, [
'nickname',
'gender',
'birthdate',
'profileImage',
]) {}

export class SignupDto extends IntersectionType(UserDto, ProfileDto) {
Expand Down
2 changes: 1 addition & 1 deletion BackEnd/src/auth/guard/bearerToken.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class BearerTokenGuard implements CanActivate {

const decoded = await this.authService.verifyToken(token);

const profile = await this.profilesService.findByPublicId(decoded.sub);
const profile = await this.profilesService.getProfile(decoded.sub);

const type = decoded.type;

Expand Down
4 changes: 2 additions & 2 deletions BackEnd/src/images/images.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Module } from '@nestjs/common';
import { ImagesController } from './images.controller';
import { ImagesService } from './images.service';
import {AuthModule} from "../auth/auth.module";
import {ProfilesModule} from "../profiles/profiles.module";
import { AuthModule } from '../auth/auth.module';
import { ProfilesModule } from '../profiles/profiles.module';

@Module({
imports: [AuthModule, ProfilesModule],
Expand Down
9 changes: 9 additions & 0 deletions BackEnd/src/posts/entities/posts.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ import {
} from 'typeorm';
import { Record } from '../../records/entities/records.entity';
import { Profile } from '../../profiles/entities/profiles.entity';
import { ApiProperty } from '@nestjs/swagger';

@Entity()
export class Post {
@ApiProperty({ example: '1', description: '테이블 id를 의미합니다.' })
@PrimaryGeneratedColumn()
id: number;

Expand All @@ -34,6 +36,13 @@ export class Post {
@Column()
deletedAt: Date;

@ApiProperty({
example: 'https://www.naver.com',
description: '게시물 url을 의미합니다.',
})
@Column()
postUrl: string;

@OneToOne(() => Record)
@JoinColumn()
record: Record;
Expand Down
52 changes: 52 additions & 0 deletions BackEnd/src/profiles/dto/create-profile.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Profile } from '../entities/profiles.entity';
import { PickType } from '@nestjs/swagger';
import { Post } from '../../posts/entities/posts.entity';

export class GetResPostUrl extends PickType(Post, ['id', 'postUrl']) {}

class GetResProfile extends PickType(Profile, [
'nickname',
'gender',
'birthdate',
'publicId',
'profileImage',
]) {}

export const GetProfileAndPosts = () => {
return {
example: {
code: null,
errorMessage: null,
data: {
profile: {
nickname: '닉네임',
gender: '남자',
birthdate: '2021-01-01',
publicId: 'adsd2daw-ad2dawd-q1323123',
profileImage:
'https://s3.ap-northeast-2.amazonaws.com/recordapp/adsd2daw-ad2dawd-q1323123',
},
posts: [
{
id: 1,
postUrl: 'https://www.naver.com',
},
{
id: 2,
postUrl: 'https://www.naver.com',
},
],
},
},
};
};

export const SuccessProfile = () => {
return {
example: {
code: null,
errorMessage: null,
data: null,
},
};
};
7 changes: 7 additions & 0 deletions BackEnd/src/profiles/dto/update-profile.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { PickType } from '@nestjs/swagger';
import { Profile } from '../entities/profiles.entity';

export class UpdateProfileDto extends PickType(Profile, [
'nickname',
'profileImage',
]) {}
5 changes: 4 additions & 1 deletion BackEnd/src/profiles/entities/profiles.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,11 @@ export class Profile {
@Generated('uuid')
publicId: string;

@ApiProperty({
example: 'https://s3.bucket.url',
description: '프로필 이미지 url을 의미합니다.',
})
@Column({ nullable: true })
@IsUrl()
profileImage: string;

@OneToOne(() => User, (user) => user.profile)
Expand Down
12 changes: 12 additions & 0 deletions BackEnd/src/profiles/exception/profile.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { HttpException } from '@nestjs/common';

export class PublicIdMismatchException extends HttpException {
constructor() {
const response = {
statusCode: 2030,
message: 'misMatch',
};
const httpCode = 400;
super(response, httpCode);
}
}
65 changes: 63 additions & 2 deletions BackEnd/src/profiles/profiles.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,68 @@
import { Controller } from '@nestjs/common';
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
UseGuards,
} from '@nestjs/common';
import { ProfilesService } from './profiles.service';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { ProfileDeco } from './decorator/profile.decorator';
import { Profile } from './entities/profiles.entity';
import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { AccessTokenGuard } from '../auth/guard/bearerToken.guard';
import { GetProfileAndPosts, SuccessProfile } from './dto/create-profile.dto';

@Controller('profiles')
@ApiTags('Profiles API')
@Controller('api/v1/profiles')
@UseGuards(AccessTokenGuard)
export class ProfilesController {
constructor(private readonly profilesService: ProfilesService) {}

@ApiOperation({ summary: '프로필을 조회한다.' })
@ApiResponse({
status: 200,
description: '프로필 조회 성공',
schema: GetProfileAndPosts(),
})
@Get(':publicId')
async getMyProfile(@Param('publicId') publicId: string) {
return this.profilesService.getProfileAndPost(publicId);
}

@ApiOperation({ summary: '프로필을 수정한다. 닉네임 또는 사진' })
@ApiBody({ type: UpdateProfileDto })
@ApiResponse({
status: 200,
description: '프로필 수정 성공',
schema: SuccessProfile(),
})
@Patch(':profileId')
async updateProfile(
@Param('profileId') profileId: string,
@Body() updateProfileDto: UpdateProfileDto,
@ProfileDeco() profile: Profile,
) {
return this.profilesService.updateProfile(
profileId,
profile.publicId,
updateProfileDto,
);
}

@ApiOperation({ summary: '프로필을 삭제한다.' })
@ApiResponse({
status: 200,
description: '프로필 삭제 성공',
schema: SuccessProfile(),
})
@Delete(':profileId')
async deleteProfile(
@Param('profileId') profileId: string,
@ProfileDeco() profile: Profile,
) {
return this.profilesService.deleteProfile(profileId, profile.publicId);
}
}
14 changes: 11 additions & 3 deletions BackEnd/src/profiles/profiles.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@ import { ProfilesService } from './profiles.service';
import { ProfilesController } from './profiles.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Profile } from './entities/profiles.entity';

import { Post } from '../posts/entities/posts.entity';
import { AuthService } from '../auth/auth.service';
import { JwtModule } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { AuthAppleService } from '../auth/auth-apple.service';
import { User } from '../users/entities/users.entity';
@Module({
imports: [TypeOrmModule.forFeature([Profile])],
imports: [
TypeOrmModule.forFeature([Profile, Post, User]),
JwtModule.register({}),
],
exports: [ProfilesService],
controllers: [ProfilesController],
providers: [ProfilesService],
providers: [ProfilesService, AuthService, UsersService, AuthAppleService],
})
export class ProfilesModule {}
59 changes: 51 additions & 8 deletions BackEnd/src/profiles/profiles.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,76 @@ import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Profile } from './entities/profiles.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { PublicIdMismatchException } from './exception/profile.exception';
import { Post } from '../posts/entities/posts.entity';

@Injectable()
export class ProfilesService {
constructor(
@InjectRepository(Post)
private readonly postsRepository: Repository<Post>,
@InjectRepository(Profile)
private readonly profilesRepository: Repository<Profile>,
) {}

async findByPublicId(publicId: string) {
async getProfileAndPost(publicId: string) {
const posts = await this.postsRepository.find({
where: {
publicId: publicId,
},
order: {
createdAt: 'DESC',
},
take: 9,
select: ['id', 'postUrl'],
});
const profile = await this.profilesRepository.findOne({
where: {
publicId,
},
select: ['nickname', 'gender', 'birthdate', 'publicId', 'profileImage'],
});
return {
profile,
posts,
};
}

return profile;
async updateProfile(
profileId: string,
publicId: string,
updateProfileDto: UpdateProfileDto,
) {
if (!this.validateProfileId(profileId, publicId)) {
throw new PublicIdMismatchException();
}
return this.profilesRepository.update({ publicId }, updateProfileDto);
}

async deleteProfile(profileId: string, publicId: string) {
if (!this.validateProfileId(profileId, publicId)) {
throw new PublicIdMismatchException();
}
return this.profilesRepository.delete({ publicId });
}

async existByNickname(nickname: string) {
const nicknameExists = await this.profilesRepository.exist({
private validateProfileId(profileId: string, publicId: string) {
return profileId === publicId;
}
async validateProfileNickname(nickname: string) {
return this.profilesRepository.exist({
where: {
nickname,
},
});
if (nicknameExists) {
return true;
}
return false;
}

async getProfile(publicId: string) {
return this.profilesRepository.findOne({
where: {
publicId,
},
});
}
}
19 changes: 10 additions & 9 deletions BackEnd/src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,22 @@ export class UsersService {
private readonly redisData: Redis,
) {}

async createUser(singupInfo: SignupDto) {
const userId = await this.redisData.get(singupInfo.mappedUserID);
async createUser(signupInfo: SignupDto) {
const userId = await this.redisData.get(signupInfo.mappedUserID);
const profile = {
nickname: singupInfo.nickname,
gender: singupInfo.gender,
birthdate: singupInfo.birthdate,
nickname: signupInfo.nickname,
gender: signupInfo.gender,
birthdate: signupInfo.birthdate,
profileImage: signupInfo.profileImage,
};
const userObj = this.usersRepository.create({
userId,
provider: singupInfo.provider,
provider: signupInfo.provider,
profile,
});
const newUesr = await this.usersRepository.save(userObj);
await this.redisData.del(singupInfo.mappedUserID);
return newUesr;
const newUser = await this.usersRepository.save(userObj);
await this.redisData.del(signupInfo.mappedUserID);
return newUser;
}

async getUserByUserIdAndProvider(userInfo: GetuserByUserIdAndProViderDto) {
Expand Down
Loading