Skip to content

Commit

Permalink
merge #133: DB 구조 변경에 따른 기존 게시글 조회/수정/삭제 및 좋아요, 신고 API 수정
Browse files Browse the repository at this point in the history
[refactor] DB 구조 변경에 따른 기존 게시글 조회/수정/삭제 및 좋아요, 신고 API 수정
  • Loading branch information
yaongmeow authored Nov 27, 2023
2 parents dc6764b + b71c2c2 commit 87dd496
Show file tree
Hide file tree
Showing 16 changed files with 366 additions and 279 deletions.
2 changes: 1 addition & 1 deletion BE/src/database/database.providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const databaseProviders = [
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
synchronize: true,
synchronize: false,
});
return dataSource.initialize();
},
Expand Down
6 changes: 6 additions & 0 deletions BE/src/postings/entities/mappings/posting-mapping.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { PrimaryGeneratedColumn } from 'typeorm';

export class PostingMapping {
@PrimaryGeneratedColumn('uuid')
id: string;
}
14 changes: 6 additions & 8 deletions BE/src/postings/entities/mappings/posting-theme.entity.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { Posting } from '../posting.entity';
import { PostingMapping } from './posting-mapping.entity';
import { Entity, JoinColumn, ManyToOne } from 'typeorm';
import { Theme } from '../tags/theme.entity';
import { Posting } from '../posting.entity';

@Entity('posting_theme')
export class PostingTheme {
@PrimaryGeneratedColumn('uuid')
id: string;

export class PostingTheme extends PostingMapping {
@ManyToOne(() => Posting, (posting) => posting.postingThemes, {
onDelete: 'CASCADE',
})
Expand All @@ -16,6 +14,6 @@ export class PostingTheme {
@ManyToOne(() => Theme, (theme) => theme.postingTheme, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'theme' })
theme: Theme;
@JoinColumn({ name: 'tag' })
tag: Theme;
}
12 changes: 5 additions & 7 deletions BE/src/postings/entities/mappings/posting-with-who.entity.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { PostingMapping } from './posting-mapping.entity';
import { Entity, JoinColumn, ManyToOne } from 'typeorm';
import { WithWho } from '../tags/with-who.entity';
import { Posting } from '../posting.entity';

@Entity('posting_with_who')
export class PostingWithWho {
@PrimaryGeneratedColumn('uuid')
id: string;

export class PostingWithWho extends PostingMapping {
@ManyToOne(() => Posting, (posting) => posting.postingWithWhos, {
onDelete: 'CASCADE',
})
Expand All @@ -16,6 +14,6 @@ export class PostingWithWho {
@ManyToOne(() => WithWho, (withWho) => withWho.postingWithWho, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'with_who' })
withWho: WithWho;
@JoinColumn({ name: 'tag' })
tag: WithWho;
}
2 changes: 1 addition & 1 deletion BE/src/postings/entities/tags/theme.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import { Entity, OneToMany } from 'typeorm';

@Entity()
export class Theme extends Tag {
@OneToMany(() => PostingTheme, (postingTheme) => postingTheme.theme)
@OneToMany(() => PostingTheme, (postingTheme) => postingTheme.tag)
postingTheme: PostingTheme[];
}
2 changes: 1 addition & 1 deletion BE/src/postings/entities/tags/with-who.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import { Tag } from './tag.entity';

@Entity('with_who')
export class WithWho extends Tag {
@OneToMany(() => PostingWithWho, (postingWithWho) => postingWithWho.withWho)
@OneToMany(() => PostingWithWho, (postingWithWho) => postingWithWho.tag)
postingWithWho: PostingWithWho[];
}
202 changes: 79 additions & 123 deletions BE/src/postings/postings.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {
Delete,
Query,
Put,
BadRequestException,
UseGuards,
Req,
} from '@nestjs/common';
import { PostingsService } from './postings.service';
import { CreatePostingDto } from './dto/create-posting.dto';
Expand All @@ -21,60 +21,23 @@ import {
ApiTags,
} from '@nestjs/swagger';
import { Posting } from './entities/posting.entity';
import {
budgets,
headcounts,
locations,
periods,
seasons,
themes,
vehicles,
withWhos,
} from './postings.types';
import { AuthGuard } from '../auth/auth.guard';
import { UsersService } from '../users/users.service';

@UseGuards(AuthGuard)
@Controller('postings')
@ApiTags('Postings API')
export class PostingsController {
constructor(
private readonly postingsService: PostingsService,
private readonly usersService: UsersService
) {}
constructor(private readonly postingsService: PostingsService) {}

@Post()
@ApiOperation({
summary: '포스팅 생성 API',
description: '새로운 포스팅을 작성한다.',
})
@ApiOkResponse({ description: 'OK', type: Posting })
async create(@Body() createPostingDto: CreatePostingDto) {
if (
new Date(createPostingDto.endDate) < new Date(createPostingDto.startDate)
) {
throw new BadRequestException(
'endDate는 startDate와 같거나 더 나중의 날짜여야 합니다.'
);
}

const user = await this.usersService.findById(''); // TODO: JWT 토큰에서 user의 id 꺼내기
const posting = await this.postingsService.createPosting(
user,
createPostingDto
);

await this.postingsService.createPostingTheme(
posting,
createPostingDto.theme
);

await this.postingsService.createPostingWithWho(
posting,
createPostingDto.withWho
);

return posting;
@ApiCreatedResponse({ description: 'Created', type: Posting })
async create(@Req() request, @Body() createPostingDto: CreatePostingDto) {
const userId = ''; // TODO: request['user'].id; (현재 id 필드 값은 닉네임)
return this.postingsService.createPosting(userId, createPostingDto);
}

// @Get()
Expand All @@ -87,65 +50,47 @@ export class PostingsController {
// //return this.postingsService.search(searchPostingDto);
// }

// @Get(':id')
// @ApiOperation({
// summary: '포스팅 로드 API',
// description: 'id 값에 해당되는 포스팅을 반환한다.',
// })
// @ApiOkResponse({ description: 'OK', type: Posting })
// async findOne(@Param('id') id: string) {
// const posting = await this.postingsService.findOne(id);
// const userId = ''; // TODO: JWT에서 userID 가져오기
// return {
// id: posting.id,
// writer: posting.writer,
// title: posting.title,
// createdAt: posting.created_at,
// thumbnail: posting.thumbnail,
// startDate: posting.start_date,
// endDate: posting.end_date,
// days: this.postingsService.createDaysList(
// posting.start_date,
// posting.days
// ),
// period: periods[posting.period] || null,
// headcount: headcounts[posting.headcount] || null,
// budget: budgets[posting.budget] || null,
// location: locations[posting.location],
// season: seasons[posting.season],
// vehicle: vehicles[posting.vehicle] || null,
// theme: posting.theme ? posting.theme.map((e) => themes[e]) : null,
// withWho: posting.with_who
// ? posting.with_who.map((e) => withWhos[e])
// : null,
// report: posting.report.length,
// liked: posting.liked.length,
// isLiked: posting.liked.some((liked) => liked.user === userId),
// isOwner: posting.writer === userId,
// };
// }
@Get(':id')
@ApiOperation({
summary: '포스팅 로드 API',
description: 'id 값에 해당되는 포스팅을 반환한다.',
})
@ApiOkResponse({ description: 'OK', type: Posting })
async findOne(@Param('id') id: string) {
const userId = ''; // TODO: request['user'].id; (현재 id 필드 값은 닉네임)
const posting = await this.postingsService.findPosting(id);

// @Put(':id')
// @ApiOperation({
// summary: '포스팅 수정 API',
// description: 'id 값에 해당되는 포스팅을 수정한다.',
// })
// @ApiOkResponse({ description: 'OK' })
// update(@Param('id') id: string, @Body() updatePostingDto: UpdatePostingDto) {
// // TODO: JWT에서 user id 가져오기
// return this.postingsService.update(id, '', updatePostingDto);
// }
return {
...posting,
days: this.createDaysList(posting.startDate, posting.days),
liked: posting.liked.length,
report: posting.report.length,
isLiked: posting.liked.some((liked) => liked.user === userId),
isOwner: posting.writer.id === userId,
};
}

// @Delete(':id')
// @ApiOperation({
// summary: '포스팅 삭제 API',
// description: 'id 값에 해당되는 포스팅을 삭제한다.',
// })
// @ApiOkResponse({ description: 'OK' })
// remove(@Param('id') id: string) {
// // TODO: JWT에서 user id 가져오기
// return this.postingsService.remove(id, '');
// }
@Put(':id')
@ApiOperation({
summary: '포스팅 수정 API',
description: 'id 값에 해당되는 포스팅을 수정한다.',
})
@ApiOkResponse({ description: 'OK' })
update(@Param('id') id: string, @Body() updatePostingDto: UpdatePostingDto) {
const userId = ''; // TODO: request['user'].id; (현재 id 필드 값은 닉네임)
return this.postingsService.updatePosting(id, userId, updatePostingDto);
}

@Delete(':id')
@ApiOperation({
summary: '포스팅 삭제 API',
description: 'id 값에 해당되는 포스팅을 삭제한다.',
})
@ApiOkResponse({ description: 'OK' })
remove(@Param('id') id: string) {
const userId = ''; // TODO: request['user'].id; (현재 id 필드 값은 닉네임)
return this.postingsService.removePosting(id, userId);
}

// @Get('/titles')
// @ApiOperation({
Expand All @@ -158,28 +103,39 @@ export class PostingsController {
// //return this.postingsService.searchByKeyWord(keyword);
// }

// @Post(':id/like')
// @ApiOperation({
// summary: '포스팅 좋아요 API',
// description:
// 'id 값에 해당되는 포스팅에 좋아요가 추가되거나 삭제된다. (토글)',
// })
// @ApiOkResponse({ description: 'OK' })
// toggleLike(@Param('id') id: string) {
// // TODO: JWT에서 사용자 ID 가져오기
// return this.postingsService.toggleLike(id, '');
// }
@Post(':id/like')
@ApiOperation({
summary: '포스팅 좋아요 API',
description:
'id 값에 해당되는 포스팅에 좋아요가 추가되거나 삭제된다. (토글)',
})
@ApiOkResponse({ description: 'OK' })
toggleLike(@Param('id') id: string) {
const userId = ''; // TODO: request['user'].id; (현재 id 필드 값은 닉네임)
return this.postingsService.toggleLike(id, userId);
}

// @Post(':id/report')
// @ApiOperation({
// summary: '게시글 신고',
// description: 'id에 해당하는 게시글을 신고한다.',
// })
// @ApiCreatedResponse({
// description: 'OK',
// })
// report(@Param('id') id: string) {
// // TODO: JWT에서 사용자 ID 가져오기
// return this.postingsService.report(id, '');
// }
@Post(':id/report')
@ApiOperation({
summary: '게시글 신고',
description: 'id에 해당하는 게시글을 신고한다.',
})
@ApiCreatedResponse({
description: 'OK',
})
report(@Param('id') id: string) {
const userId = ''; // TODO: request['user'].id; (현재 id 필드 값은 닉네임)
return this.postingsService.report(id, userId);
}

private createDaysList(startDate: Date, days: number) {
const weekdays = ['일', '월', '화', '수', '목', '금', '토'];
const standardDate = new Date(startDate);

return Array.from({ length: days }, (_, index) => {
const date = new Date(startDate);
date.setDate(standardDate.getDate() + index);
return `${date.getDate()}${weekdays[date.getDay()]}`;
});
}
}
4 changes: 0 additions & 4 deletions BE/src/postings/postings.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,12 @@ import { VehiclesRepository } from './repositories/tags/vehicles.repository';
import { WithWhosRepository } from './repositories/tags/with-whos.repository';
import { PostingThemesRepository } from './repositories/mappings/posting-themes.repository';
import { PostingWithWhosRepository } from './repositories/mappings/posting-with-whos.repository';
import { UsersService } from '../users/users.service';
import { UsersModule } from '../users/users.module';
import { StorageService } from '../storage/storage.service';

@Module({
imports: [DatabaseModule, UsersModule],
controllers: [PostingsController],
providers: [
UsersService,
StorageService,
...postingsProviders,
PostingsService,
PostingsRepository,
Expand Down
Loading

0 comments on commit 87dd496

Please sign in to comment.