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

[BE/#94] PATCH /posts/{id} API 구현 #96

Merged
merged 4 commits into from
Nov 21, 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 BE/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ async function bootstrap() {
],
}),
});

app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
app.useGlobalPipes(new ValidationPipe());
setupSwagger(app);
Expand Down
22 changes: 21 additions & 1 deletion BE/src/post/post.controller.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import {
Body,
Controller,
Get,
HttpCode,
HttpException,
Param,
Post,
Patch,
Req,
Res,
Post,
UploadedFiles,
UseInterceptors,
ValidationPipe,
} from '@nestjs/common';
import { PostService } from './post.service';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { UpdatePostDto } from './postUpdateDto';
import { FilesInterceptor } from '@nestjs/platform-express';
import { CreatePostDto } from './createPost.dto';
import { MultiPartBody } from '../utils/multiPartBody.decorator';
Expand Down Expand Up @@ -56,4 +62,18 @@ export class PostController {
throw new HttpException('서버 오류입니다.', 500);
}
}

@Patch('/:id')
@ApiOperation({ summary: 'fix post context', description: '게시글 수정' })
async postModify(@Param('id') id: number, @Body() body: UpdatePostDto) {
const isFixed = await this.postService.updatePostById(id, body);

if (isFixed) {
return HttpCode(200);
} else if (isFixed === false) {
throw new HttpException('게시글이 존재하지 않습니다.', 404);
} else {
throw new HttpException('서버 오류입니다.', 500);
}
}
}
50 changes: 47 additions & 3 deletions BE/src/post/post.service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { Injectable } from '@nestjs/common';
import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PostEntity } from '../entities/post.entity';
import { Repository } from 'typeorm';
import { UpdatePostDto } from './postUpdateDto';
import { validate } from 'class-validator';
import { PostImageEntity } from 'src/entities/postImage.entity';
import { S3Handler } from '../utils/S3Handler';
import { UserEntity } from '../entities/user.entity';
import { PostImageEntity } from '../entities/postImage.entity';

@Injectable()
export class PostService {
Expand Down Expand Up @@ -34,7 +36,6 @@ export class PostService {
};
posts.push(post);
});
// console.log(posts);
return posts;
}

Expand All @@ -59,6 +60,49 @@ export class PostService {
}
}

async changeImages(postId: number, images: string[]) {
try {
await this.postImageRepository.delete({ post_id: postId });
images.forEach(async (image) => {
await this.postImageRepository.save({
post_id: postId,
image_url: image,
});
});
} catch {
throw new HttpException('서버 오류입니다.', 500);
}
}

async changeExceptImages(postId: number, updatePostDto: UpdatePostDto) {
try {
await this.postRepository.update({ id: postId }, updatePostDto);
} catch {
throw new HttpException('서버 오류입니다.', 500);
}
}

async updatePostById(postId: number, updatePostDto: UpdatePostDto) {
const isDataExists = await this.postRepository.findOne({
where: { id: postId },
});

const isChangingImages = 'images' in updatePostDto; // images 가 존재여부 확인

try {
if (!isDataExists) {
Copy link
Member

Choose a reason for hiding this comment

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

세세한 경우를 잘 나누어서 구현하신 것이 좋네요

return false;
} else if (!isChangingImages) {
await this.changeExceptImages(postId, updatePostDto);
return true;
} else {
await this.changeExceptImages(postId, updatePostDto);
await this.changeImages(postId, updatePostDto.images);
return true;
}
} catch {
return null;

async uploadImages(files: Express.Multer.File[]): Promise<string[]> {
const fileLocation: Array<string> = [];
for (const file of files) {
Expand Down
20 changes: 20 additions & 0 deletions BE/src/post/postUpdateDto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { IsArray, IsNumber, IsOptional, IsString } from 'class-validator';

export class UpdatePostDto {
@IsOptional() // 이 필드는 선택적으로 업데이트할 수 있도록 설정
@IsString()
title?: string;

@IsOptional()
@IsString()
contents?: string;

@IsOptional()
@IsNumber() // 전화번호 형식 검증
price?: number;

@IsArray()
@IsOptional()
@IsString({ each: true })
images?: string[];
}
Loading