Skip to content

Commit

Permalink
Merge pull request #370 from boostcampwm2023/server/feature/352
Browse files Browse the repository at this point in the history
노래 삭제 API 구현
  • Loading branch information
khw3754 authored Jan 11, 2024
2 parents 4f93dd3 + 8d7369b commit 77199be
Show file tree
Hide file tree
Showing 6 changed files with 123 additions and 6 deletions.
2 changes: 2 additions & 0 deletions server/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ export const contentTypeHandler: Record<string, string> = {
export const getTimeStamp = (): number => {
return new Date().getTime();
};

export const SLICE_COUNT: number = 'https://catchy-tape-bucket2.kr.object.ncloudstorage.com/'.length;
18 changes: 18 additions & 0 deletions server/src/entity/music.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,22 @@ export class Music extends BaseEntity {
},
});
}

static async isExistMusicId(musicId: string): Promise<boolean> {
const count: number = await this.count({ where: { music_id: musicId } });
if (count === 0) {
return false;
}
return true;
}

static async isMusicOwner(musicId: string, userId: string): Promise<boolean> {
const count: number = await this.count({
where: { music_id: musicId, user: { user_id: userId } },
});
if (count === 0) {
return false;
}
return true;
}
}
4 changes: 3 additions & 1 deletion server/src/entity/music_playlist.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ export class Music_Playlist extends BaseEntity {
@PrimaryGeneratedColumn()
music_playlist_id: number;

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

Expand Down
4 changes: 3 additions & 1 deletion server/src/entity/recent_played.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ export class Recent_Played extends BaseEntity {
@PrimaryGeneratedColumn()
recent_played_id: number;

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

Expand Down
16 changes: 13 additions & 3 deletions server/src/music/music.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
ValidationPipe,
Query,
Logger,
Delete,
} from '@nestjs/common';
import { MusicService } from './music.service';
import { HTTP_STATUS_CODE } from 'src/httpStatusCode.enum';
Expand All @@ -22,9 +23,7 @@ import { Music } from 'src/entity/music.entity';
export class MusicController {
private readonly logger = new Logger('Music');
private objectStorage: AWS.S3;
constructor(
private readonly musicService: MusicService,
) {}
constructor(private readonly musicService: MusicService) {}

@Post()
@UsePipes(ValidationPipe)
Expand Down Expand Up @@ -103,4 +102,15 @@ export class MusicController {
this.logger.log(`GET /musics/search - keyword=${keyword}`);
return this.musicService.getCertainKeywordNicknameUser(keyword);
}

@Delete()
@UseGuards(AuthGuard())
@HttpCode(HTTP_STATUS_CODE.SUCCESS)
async deleteMusic(
@Req() req,
@Body('music_id') music_id: string,
): Promise<string> {
const userId = req.user.user_id;
return await this.musicService.deleteMusicById(music_id, userId);
}
}
85 changes: 84 additions & 1 deletion server/src/music/music.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import { Repository, DataSource } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { MusicCreateDto } from 'src/dto/musicCreate.dto';
import { Music } from 'src/entity/music.entity';
import { Genres } from 'src/constants';
import { Genres, SLICE_COUNT } from 'src/constants';
import { CatchyException } from 'src/config/catchyException';
import { ERROR_CODE } from 'src/config/errorCode.enum';
import { UploadService } from 'src/upload/upload.service';
import { NcloudConfigService } from 'src/config/ncloud.config';
import { AWSError } from 'aws-sdk';
import { DeleteObjectOutput } from 'aws-sdk/clients/s3';

@Injectable()
export class MusicService {
Expand Down Expand Up @@ -187,4 +188,86 @@ export class MusicService {
);
}
}

async deleteMusicById(musicId: string, userId: string): Promise<string> {
if (!(await Music.isMusicOwner(musicId, userId))) {
this.logger.error(`music.service - deleteMusicById : NOT_EXIST_MUSIC`);
throw new CatchyException(
'NOT_EXIST_MUSIC',
HTTP_STATUS_CODE.SERVER_ERROR,
ERROR_CODE.NOT_EXIST_MUSIC,
);
}

try {
const music: Music = await Music.getMusicById(musicId);
this.musicRepository.delete(music.music_id);

const musicFilePath: string = music.music_file.slice(SLICE_COUNT, SLICE_COUNT + 41);
const coverFilePath: string = music.cover.slice(SLICE_COUNT, SLICE_COUNT + 46);

if (musicFilePath) this.deleteFolder(musicFilePath);
if (coverFilePath) this.deleteFolder(coverFilePath);

return music.music_id;
} catch {
this.logger.error(`music.service - deleteMusicById : SERVICE_ERROR`);
throw new CatchyException(
'SERVICE_ERROR',
HTTP_STATUS_CODE.SERVER_ERROR,
ERROR_CODE.SERVICE_ERROR,
);
}
}

async deleteFolder(folderPath) {
let params = {
Bucket: 'catchy-tape-bucket2',
Delete: {
Objects: [],
},
};

// 폴더 내의 파일들을 삭제할 객체 목록에 추가
const filesInFolder = await this.listFilesInFolder(folderPath);
filesInFolder.forEach((file) => {
params.Delete.Objects.push({ Key: file.Key });
});

try {
// 폴더 내의 파일들을 삭제
await this.objectStorage.deleteObjects(params).promise();

// 폴더를 삭제
await this.objectStorage
.deleteObject({ Bucket: 'catchy-tape-bucket2', Key: folderPath })
.promise();
} catch (error) {
this.logger.error(`music.service - deleteFolder : SERVICE_ERROR`);
throw new CatchyException(
'SERVICE_ERROR',
HTTP_STATUS_CODE.SERVER_ERROR,
ERROR_CODE.SERVICE_ERROR,
);
}
}

async listFilesInFolder(folderPath) {
let params = {
Bucket: 'catchy-tape-bucket2',
Prefix: folderPath,
};

try {
const data = await this.objectStorage.listObjectsV2(params).promise();
return data.Contents;
} catch (error) {
this.logger.error(`music.service - listFilesInFolder : SERVICE_ERROR`);
throw new CatchyException(
'SERVICE_ERROR',
HTTP_STATUS_CODE.SERVER_ERROR,
ERROR_CODE.SERVICE_ERROR,
);
}
}
}

0 comments on commit 77199be

Please sign in to comment.