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/#90] Post /posts API 구현 #98

Merged
merged 9 commits into from
Nov 21, 2023
35 changes: 35 additions & 0 deletions BE/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions BE/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^7.1.15",
"@nestjs/typeorm": "^10.0.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"multer-s3": "^3.0.1",
"mysql2": "^3.6.3",
"nest-winston": "^1.9.4",
Expand Down
12 changes: 10 additions & 2 deletions BE/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Module, Logger } from '@nestjs/common';
import { Module, Logger, ValidationPipe } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { WinstonModule } from 'nest-winston';
Expand All @@ -9,6 +9,7 @@ import { AppService } from './app.service';
import { winstonOptions, dailyOption } from './config/winston.config';
import { MysqlConfigProvider } from './config/mysql.config';
import { PostModule } from './post/post.module';
import { APP_PIPE } from '@nestjs/core';

@Module({
imports: [
Expand All @@ -25,6 +26,13 @@ import { PostModule } from './post/post.module';
PostModule,
],
controllers: [AppController],
providers: [AppService, Logger],
providers: [
AppService,
Logger,
{
provide: APP_PIPE,
useClass: ValidationPipe,
},
],
})
export class AppModule {}
4 changes: 2 additions & 2 deletions BE/src/entities/post.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class PostEntity {
user: UserEntity;

@Column({ type: 'tinyint', nullable: false })
status: number;
status: boolean;

@Column({ type: 'datetime', nullable: false })
start_date: Date;
Expand All @@ -43,7 +43,7 @@ export class PostEntity {
end_date: Date;

@Column({ type: 'tinyint', nullable: false })
is_request: number;
is_request: boolean;

@CreateDateColumn({
type: 'timestamp',
Expand Down
2 changes: 2 additions & 0 deletions BE/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { setupSwagger } from './config/swagger.config';
import { WINSTON_MODULE_NEST_PROVIDER, WinstonModule } from 'nest-winston';
import { dailyOption, winstonOptions } from './config/winston.config';
import * as winstonDaily from 'winston-daily-rotate-file';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
const app = await NestFactory.create(AppModule, {
Expand All @@ -16,6 +17,7 @@ async function bootstrap() {
}),
});
app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
app.useGlobalPipes(new ValidationPipe());
setupSwagger(app);
await app.listen(3000);
}
Expand Down
22 changes: 22 additions & 0 deletions BE/src/post/createPost.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { IsBoolean, IsNumber, IsString, ValidateIf } from 'class-validator';

export class CreatePostDto {
@IsString()
title: string;

@IsString()
contents: string;

@IsNumber()
@ValidateIf((object) => object.is_request === false)
price: number;

@IsBoolean()
is_request: boolean;

@IsString()
start_date: string;

@IsString()
end_date: string;
}
32 changes: 31 additions & 1 deletion BE/src/post/post.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
import { Controller, Get, HttpException, Param } from '@nestjs/common';
import {
Controller,
Get,
HttpException,
Param,
Post,
UploadedFiles,
UseInterceptors,
ValidationPipe,
} from '@nestjs/common';
import { PostService } from './post.service';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { FilesInterceptor } from '@nestjs/platform-express';
import { CreatePostDto } from './createPost.dto';
import { MultiPartBody } from '../utils/multiPartBody.decorator';

@Controller('posts')
@ApiTags('posts')
Expand All @@ -13,6 +25,24 @@ export class PostController {
return posts;
}

@Post()
@UseInterceptors(FilesInterceptor('image', 12))
async postsCreate(
@UploadedFiles() files: Array<Express.Multer.File>,
@MultiPartBody(
'profile_info',
new ValidationPipe({ validateCustomDecorators: true }),
)
createPostDto: CreatePostDto,
) {
const userId: string = 'qwe';
let imageLocation: Array<string> = [];
if (createPostDto.is_request === false && files !== undefined) {
imageLocation = await this.postService.uploadImages(files);
}
await this.postService.createPost(imageLocation, createPostDto, userId);
}

@Get('/:id')
@ApiOperation({ summary: 'search for post', description: '게시글 상세 조회' })
async postDetails(@Param('id') id: number) {
Expand Down
9 changes: 7 additions & 2 deletions BE/src/post/post.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ import { PostController } from './post.controller';
import { PostService } from './post.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PostEntity } from '../entities/post.entity';
import { S3Handler } from '../utils/S3Handler';
import { UserEntity } from '../entities/user.entity';
import { PostImageEntity } from '../entities/postImage.entity';

@Module({
imports: [TypeOrmModule.forFeature([PostEntity])],
imports: [
TypeOrmModule.forFeature([PostEntity, UserEntity, PostImageEntity]),
],
controllers: [PostController],
providers: [PostService],
providers: [PostService, S3Handler],
})
export class PostModule {}
45 changes: 45 additions & 0 deletions BE/src/post/post.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@ import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PostEntity } from '../entities/post.entity';
import { Repository } from 'typeorm';
import { S3Handler } from '../utils/S3Handler';
import { UserEntity } from '../entities/user.entity';
import { PostImageEntity } from '../entities/postImage.entity';

@Injectable()
export class PostService {
constructor(
@InjectRepository(PostEntity)
private postRepository: Repository<PostEntity>,
@InjectRepository(UserEntity)
private userRepository: Repository<UserEntity>,
@InjectRepository(PostImageEntity)
private postImageRepository: Repository<PostImageEntity>,
private s3Handler: S3Handler,
) {}
async getPosts() {
const res = await this.postRepository.find();
Expand Down Expand Up @@ -50,4 +58,41 @@ export class PostService {
return null;
}
}

async uploadImages(files: Express.Multer.File[]): Promise<string[]> {
const fileLocation: Array<string> = [];
for (const file of files) {
fileLocation.push(await this.s3Handler.uploadFile(file));
}
return fileLocation;
}

async createPost(imageLocations, createPostDto, userHash) {
const post = new PostEntity();
const user = await this.userRepository.findOne({
where: { user_hash: userHash },
});
post.title = createPostDto.title;
post.contents = createPostDto.contents;
post.price = createPostDto.price;
post.is_request = createPostDto.is_request;
post.start_date = createPostDto.start_date;
post.end_date = createPostDto.end_date;
post.status = true;
post.user_id = user.id;
// 이미지 추가
const res = await this.postRepository.save(post);
if (res.is_request === false) {
await this.createImages(imageLocations, res.id);
}
}

async createImages(imageLocations: Array<string>, postId: number) {
for (const imageLocation of imageLocations) {
const postImageEntity = new PostImageEntity();
postImageEntity.image_url = imageLocation;
postImageEntity.post_id = postId;
await this.postImageRepository.save(postImageEntity);
}
}
}
10 changes: 10 additions & 0 deletions BE/src/utils/multiPartBody.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const MultiPartBody = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
const request: Request = ctx.switchToHttp().getRequest();
const body = request.body;

return data ? JSON.parse(body?.[data]) : body;
},
);
Copy link
Collaborator

Choose a reason for hiding this comment

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

커스텀 데코레이터를 사용해서 request.body 를 파싱한 과정이 좋네요~

Loading