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

플레이리스트 조회 API #153

Merged
merged 6 commits into from
Nov 23, 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
41 changes: 36 additions & 5 deletions server/src/entity/music_playlist.entity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { BaseEntity, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import {
BaseEntity,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { Music } from './music.entity';
import { Playlist } from './playlist.entity';

Expand All @@ -8,10 +14,35 @@ export class Music_Playlist extends BaseEntity {
music_playlist_id: number;

@ManyToOne(() => Music, (music) => music.music_playlist)
@JoinColumn({name: 'music_id'})
music: Music
@JoinColumn({ name: 'music_id' })
music: Music;

@ManyToOne(() => Playlist, (playlist) => playlist.music_playlist)
@JoinColumn({name: 'playlist_id'})
playlist: Playlist
@JoinColumn({ name: 'playlist_id' })
playlist: Playlist;

static async getMusicListByPlaylistId(playlistId: number): Promise<Music[]> {
return this.find({
Copy link
Member

Choose a reason for hiding this comment

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

이게 엔티티에 들어간다는게 생소하지만 Custom Repository 만드는 것보다 현재는 이게 나을 것 같아요 👍

relations: {
music: { user: true },
},
where: {
playlist: { playlist_Id: playlistId },
},
select: {
music: {
musicId: true,
title: true,
cover: true,
musicFile: true,
genre: true,
user: { user_id: true, nickname: true },
},
music_playlist_id: false,
},
order: {
music_playlist_id: 'DESC',
},
}).then((a: Music_Playlist[]) => a.map((b) => b.music));
}
}
12 changes: 12 additions & 0 deletions server/src/entity/playlist.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,16 @@ export class Playlist extends BaseEntity {

@OneToMany(() => Music_Playlist, (music_playlist) => music_playlist.playlist)
music_playlist: Music_Playlist[];

static async getPlaylistsByUserId(userId: string): Promise<Playlist[]> {
return this.find({
select: { playlist_Id: true, playlist_title: true },
where: {
user: { user_id: userId },
},
order: {
updated_at: 'DESC',
},
});
}
}
24 changes: 24 additions & 0 deletions server/src/playlist/playlist.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
Body,
Controller,
Get,
HttpCode,
Param,
Post,
Expand All @@ -13,6 +14,8 @@ import { PlaylistService } from './playlist.service';
import { AuthGuard } from '@nestjs/passport';
import { HTTP_STATUS_CODE } from 'src/httpStatusCode.enum';
import { PlaylistCreateDto } from 'src/dto/playlistCreate.dto';
import { Playlist } from 'src/entity/playlist.entity';
import { Music } from 'src/entity/music.entity';

@Controller('playlists')
export class PlaylistController {
Expand Down Expand Up @@ -51,4 +54,25 @@ export class PlaylistController {
);
return { music_playlist_id: music_playlist_id };
}

@Get()
@UseGuards(AuthGuard())
@HttpCode(HTTP_STATUS_CODE.SUCCESS)
async getUserPlaylists(@Req() req): Promise<Playlist[]> {
const userId: string = req.user.user_id;
const playlists: Playlist[] =
await this.playlistService.getUserPlaylists(userId);
return playlists;
}

@Get(':playlistId')
@UseGuards(AuthGuard())
@HttpCode(HTTP_STATUS_CODE.SUCCESS)
async getPlaylistMusics(
@Req() req,
@Param('playlistId') playlistId: number,
): Promise<Music[]> {
const userId: string = req.user.user_id;
return await this.playlistService.getPlaylistMusics(userId, playlistId);
}
}
121 changes: 96 additions & 25 deletions server/src/playlist/playlist.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,21 @@ export class PlaylistService {
userId: string,
playlistCreateDto: PlaylistCreateDto,
): Promise<number> {
const title: string = playlistCreateDto.title;
const newPlaylist: Playlist = this.playlistRepository.create({
playlist_title: title,
created_at: new Date(),
updated_at: new Date(),
user: { user_id: userId },
});
try {
const title: string = playlistCreateDto.title;
const newPlaylist: Playlist = this.playlistRepository.create({
playlist_title: title,
created_at: new Date(),
updated_at: new Date(),
user: { user_id: userId },
});

const result: Playlist = await this.playlistRepository.save(newPlaylist);
const playlistId: number = result.playlist_Id;
return playlistId;
const result: Playlist = await this.playlistRepository.save(newPlaylist);
const playlistId: number = result.playlist_Id;
return playlistId;
} catch {
throw new HttpException('SERVER_ERROR', HTTP_STATUS_CODE.SERVER_ERROR);
}
}

async addMusicToPlaylist(
Expand All @@ -52,34 +56,101 @@ export class PlaylistService {
throw new HttpException('NOT_EXIST_MUSIC', HTTP_STATUS_CODE.BAD_REQUEST);
}

// 이미 추가된 음악인지 확인
if (await this.isAlreadyAdded(playlistId, musicId)) {
throw new HttpException('ALREADY_ADDED', HTTP_STATUS_CODE.BAD_REQUEST);
}

// 관계테이블에 추가
const new_music_playlist: Music_Playlist =
this.music_playlistRepository.create({
try {
const new_music_playlist: Music_Playlist =
this.music_playlistRepository.create({
music: { musicId: musicId },
playlist: { playlist_Id: playlistId },
});

const result: Music_Playlist =
await this.music_playlistRepository.save(new_music_playlist);
this.setUpdatedAtNow(playlistId);
return result.music_playlist_id;
} catch {
throw new HttpException('SERVER_ERROR', HTTP_STATUS_CODE.SERVER_ERROR);
}
}

async isAlreadyAdded(playlistId: number, musicId: number): Promise<boolean> {
try {
const count: number = await this.music_playlistRepository.countBy({
music: { musicId: musicId },
playlist: { playlist_Id: playlistId },
});

const result: Music_Playlist =
await this.music_playlistRepository.save(new_music_playlist);
return result.music_playlist_id;
return count !== 0;
} catch {
throw new HttpException('SERVER_ERROR', HTTP_STATUS_CODE.SERVER_ERROR);
}
}

async isExistPlaylistOnUser(
playlistId: number,
userId: string,
): Promise<boolean> {
const playlistCount: number = await this.playlistRepository.countBy({
playlist_Id: playlistId,
user: { user_id: userId },
});
return playlistCount !== 0;
try {
const playlistCount: number = await this.playlistRepository.countBy({
playlist_Id: playlistId,
user: { user_id: userId },
});
return playlistCount !== 0;
} catch {
throw new HttpException('SERVER_ERROR', HTTP_STATUS_CODE.SERVER_ERROR);
}
}

async isExistMusic(musicId: number): Promise<boolean> {
const musicCount: number = await this.MusicRepository.countBy({
musicId: musicId,
});
try {
const musicCount: number = await this.MusicRepository.countBy({
musicId: musicId,
});

return musicCount !== 0;
} catch {
throw new HttpException('SERVER_ERROR', HTTP_STATUS_CODE.SERVER_ERROR);
}
}

return musicCount !== 0;
async setUpdatedAtNow(playlistId: number): Promise<void> {
try {
const targetPlaylist: Playlist = await this.playlistRepository.findOne({
where: { playlist_Id: playlistId },
});
targetPlaylist.updated_at = new Date();
this.playlistRepository.save(targetPlaylist);
} catch {
throw new HttpException('SERVER_ERROR', HTTP_STATUS_CODE.SERVER_ERROR);
}
}

async getUserPlaylists(userId: string): Promise<Playlist[]> {
Copy link
Member

Choose a reason for hiding this comment

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

DB에 접근하는 코드 불러오는 거니까 예외 처리 (혹시나 DB로의 접근이 실패할 경우?) try-catch 넣어주시면 좋겠습니당 😊

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

반영하고 merge 하겠습니다!

try {
return Playlist.getPlaylistsByUserId(userId);
} catch {
throw new HttpException('SERVER_ERROR', HTTP_STATUS_CODE.SERVER_ERROR);
}
}

async getPlaylistMusics(
userId: string,
playlistId: number,
): Promise<Music[]> {
if (!(await this.isExistPlaylistOnUser(playlistId, userId))) {
throw new HttpException(
'NOT_EXIST_PLAYLIST_ON_USER',
HTTP_STATUS_CODE.BAD_REQUEST,
);
}
try {
return Music_Playlist.getMusicListByPlaylistId(playlistId);
} catch {
throw new HttpException('SERVER_ERROR', HTTP_STATUS_CODE.SERVER_ERROR);
}
}
}
Loading