Skip to content

Commit

Permalink
Merge pull request #96 from boostcampwm2023/BE-patchPost-#94
Browse files Browse the repository at this point in the history
[BE/#94] PATCH /posts/{id} API 구현
  • Loading branch information
koomin1227 authored Nov 21, 2023
2 parents bf6f3c7 + eac58ee commit 50d983c
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 4 deletions.
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) {
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[];
}

0 comments on commit 50d983c

Please sign in to comment.