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

Feat/user post #88

Merged
merged 10 commits into from
Aug 25, 2024
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
10 changes: 8 additions & 2 deletions src/main/nest/domain/place/service/place.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@ export class PlaceService {
const isPlaceData = places.length === 0 ? false : places;
if (isPlaceData) throw new ConflictException('μž…λ ₯ν•˜μ‹  μž₯μ†Œκ°€ 이미 μ‘΄μž¬ν•©λ‹ˆλ‹€.');

const categoryArray = category.split('>').map((depth) => depth.trim());

let isCategoryData = await this.prismaService.categories.findFirst({
where: { name: category.split('>')[1].trim() },
where: { name: categoryArray[1] },
});
let createCategory: Categories;
if (!isCategoryData) {
createCategory = await this.prismaService.categories.create({
data: {
name: category.split('>')[1].trim(),
name: categoryArray[1],
type: categoryName,
code: categoryCode,
},
Expand All @@ -37,6 +39,10 @@ export class PlaceService {
telephone,
x,
y,
depth1: categoryArray[0],
depth2: categoryArray[1],
depth3: categoryArray[2],
depth4: categoryArray[3],
categoryId: isCategoryData.id,
},
});
Expand Down
55 changes: 52 additions & 3 deletions src/main/nest/domain/post/controller/post.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,23 @@ import {
Param,
Post,
Get,
Patch,
Delete,
} from '@nestjs/common';
import { ApiCreatedResponse, ApiNotFoundResponse, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import {
ApiBadRequestResponse,
ApiCreatedResponse,
ApiForbiddenResponse,
ApiNotFoundResponse,
ApiOkResponse,
ApiOperation,
ApiResponse,
ApiTags,
ApiUnauthorizedResponse,
} from '@nestjs/swagger';
import { PostService } from '../service/post.service';
import { CreatePostRequestDto, FindOnePostResponseDto } from '../../../global/dto';
import { GetUserId, ApiGuard, ApiCreatePost } from '../../../global/decorator';
import { CreatePostRequestDto, FindOnePostResponseDto, UpdatePostRequestDto } from '../../../global/dto';
import { GetUserId, ApiGuard, ApiCreatePost, ApiUpdatePost } from '../../../global/decorator';

@ApiTags('Post')
@Controller('posts')
Expand Down Expand Up @@ -42,4 +54,41 @@ export class PostController {
async findOnePost(@Param('id', ParseIntPipe) id: number) {
return await this.postService.findOnePost(id);
}

@Get(':id/check')
@ApiOperation({ summary: 'μœ μ € κ²Œμ‹œλ¬Ό μˆ˜μ • 체크' })
@ApiOkResponse({ description: 'μˆ˜μ •κ°€λŠ₯ ν•©λ‹ˆλ‹€' })
@ApiBadRequestResponse({ description: 'ν•΄λ‹Ή κ²Œμ‹œλ¬Όμ€ μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€' })
@ApiForbiddenResponse({ description: 'κ²Œμ‹œλ¬Όμ€ 24μ‹œκ°„ 이내에 μˆ˜μ •μ΄ κ°€λŠ₯ν•΄μš”' })
@ApiResponse({ status: 423, description: 'λ‹€λ₯Έ μ‚¬μš©μžμ˜ λ°˜μ‘(λŒ“κΈ€)이 μžˆλŠ” 글은 μˆ˜μ •ν•  수 μ—†μ–΄μš”' })
async checkPost(@Param('id', ParseIntPipe) id: number) {
return await this.postService.checkPost(id);
}

@Patch(':id')
@ApiGuard()
@ApiUpdatePost()
@ApiOperation({ summary: 'μœ μ € κ²Œμ‹œλ¬Ό μˆ˜μ •' })
@ApiOkResponse({ description: 'μˆ˜μ •λ˜μ—ˆμŠ΅λ‹ˆλ‹€' })
@ApiBadRequestResponse({ description: 'μ΅œλŒ€ 5κ°œκΉŒμ§€ μ—…λ‘œλ“œ κ°€λŠ₯ν•©λ‹ˆλ‹€.' })
@ApiUnauthorizedResponse({ description: 'μž‘μ„±μžκ°€ μ•„λ‹™λ‹ˆλ‹€' })
@ApiNotFoundResponse({ description: 'λŒ€ν‘œ μ΄λ―Έμ§€λŠ” ν•„μˆ˜μž…λ‹ˆλ‹€.' })
async updatePost(
@GetUserId() userId: number,
@Param('id', ParseIntPipe) id: number,
@UploadedFiles() files: Array<Express.Multer.File>,
@Body() dto: UpdatePostRequestDto,
) {
return await this.postService.updatePost(userId, id, files, dto);
}

@Delete(':id')
@ApiGuard()
@ApiOperation({ summary: 'μœ μ € κ²Œμ‹œλ¬Ό μ‚­μ œ' })
@ApiOkResponse({ description: 'μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€' })
@ApiUnauthorizedResponse({ description: 'μž‘μ„±μžκ°€ μ•„λ‹™λ‹ˆλ‹€' })
@ApiNotFoundResponse({ description: 'ν•΄λ‹Ή κ²Œμ‹œλ¬Όμ€ μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€' })
async deletePost(@GetUserId() userId: number, @Param('id', ParseIntPipe) id: number) {
return await this.postService.deletePost(userId, id);
}
}
96 changes: 93 additions & 3 deletions src/main/nest/domain/post/service/post.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import {
BadRequestException,
ForbiddenException,
HttpException,
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../../../global/prisma/prisma.service';
import { S3Service } from '../../../global/s3/s3.service';
import { CreatePostRequestDto } from '../../../global/dto';
import { CreatePostRequestDto, UpdatePostRequestDto } from '../../../global/dto';
import * as path from 'path';
import { PlaceService } from '../../place/service/place.service';

Expand Down Expand Up @@ -49,7 +56,7 @@ export class PostService {

async findOnePost(id: number) {
const postData = await this.prismaService.posts.findFirst({
where: { id },
where: { id, deletedAt: null },
select: {
id: true,
content: true,
Expand All @@ -74,6 +81,7 @@ export class PostService {
roadAddress: true,
x: true,
y: true,
categories: { select: { name: true } },
},
},
starRatings: {
Expand Down Expand Up @@ -107,4 +115,86 @@ export class PostService {
};
return result;
}

async checkPost(id: number) {
const postData = await this.prismaService.posts.findFirst({
where: { id, deletedAt: null },
select: {
content: true,
thumbnailUrl: true,
imageUrl: true,
menuTag: true,
keywordTag: true,
placeId: true,
ratingId: true,
userId: true,
createdAt: true,
comments: { select: { userId: true } },
},
});
if (!postData) {
throw new BadRequestException('ν•΄λ‹Ή κ²Œμ‹œλ¬Όμ€ μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€');
}

const createdTime = new Date(postData.createdAt);
const currentTime = new Date(new Date().getTime() + 9 * 60 * 60 * 1000);
const oneDay = 24 * 60 * 60 * 1000;
if (!(currentTime.getTime() - createdTime.getTime() < oneDay)) {
throw new ForbiddenException('κ²Œμ‹œλ¬Όμ€ 24μ‹œκ°„ 이내에 μˆ˜μ •μ΄ κ°€λŠ₯ν•΄μš”');
}

const isComments = postData.comments.some((comment) => comment.userId !== postData.userId);
if (isComments) {
throw new HttpException('λ‹€λ₯Έ μ‚¬μš©μžμ˜ λ°˜μ‘(λŒ“κΈ€)이 μžˆλŠ” 글은 μˆ˜μ •ν•  수 μ—†μ–΄μš”', 423);
}

return { message: 'μˆ˜μ •κ°€λŠ₯ ν•©λ‹ˆλ‹€', postData };
}

async updatePost(userId: number, id: number, files: Express.Multer.File[], dto: UpdatePostRequestDto) {
const { postData } = await this.checkPost(id);

if (Number(userId) !== Number(postData.userId)) throw new UnauthorizedException('μž‘μ„±μžκ°€ μ•„λ‹™λ‹ˆλ‹€');

let s3Upload = [];
if (files && files.length > 0) {
const S3URL = this.configService.get<string>('ENV_AWS_S3_URL');
const uploadToimage = files.map(async (file) => {
const key = `places/${id.toString()}/${Date.now()}-${Math.random().toString(16).slice(2)}${path.extname(file.originalname)}`;
await this.s3Service.uploadS3(key, file.buffer, file.mimetype);
return S3URL + key;
});
s3Upload = await Promise.all(uploadToimage);
}

let menuTagId = undefined;
if (dto.menuTag && dto.menuTag.length > 0) {
const menuData = await this.placeService.placeAddMenus(dto.menuTag, Number(postData.placeId));
menuTagId = menuData.map((menu) => menu.id.toString()).join(',');
}

await this.prismaService.starRatings.update({
where: { id: Number(postData.ratingId) },
data: { star: dto.starRating },
});
await this.prismaService.posts.update({
where: { id },
data: {
content: dto.content && dto.content.length > 0 ? dto.content : postData.content,
thumbnailUrl: s3Upload.length > 0 ? s3Upload[0] : postData.thumbnailUrl,
imageUrl: s3Upload.length > 1 ? s3Upload.slice(1).toString() : null,
menuTag: menuTagId !== undefined ? menuTagId : postData.menuTag,
keywordTag: dto.keywordTag && dto.keywordTag.length > 0 ? dto.keywordTag : postData.keywordTag,
},
});
return { message: 'μˆ˜μ •λ˜μ—ˆμŠ΅λ‹ˆλ‹€' };
}

async deletePost(userId: number, id: number) {
const postData = await this.prismaService.posts.findFirst({ where: { id, deletedAt: null } });
if (!postData) throw new NotFoundException('ν•΄λ‹Ή κ²Œμ‹œλ¬Όμ€ μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€');
if (Number(userId) !== Number(postData.userId)) throw new UnauthorizedException('μž‘μ„±μžκ°€ μ•„λ‹™λ‹ˆλ‹€');
await this.prismaService.posts.update({ where: { id }, data: { deletedAt: new Date() } });
return { message: 'μ‚­μ œλ˜μ—ˆμŠ΅λ‹ˆλ‹€' };
}
}
12 changes: 12 additions & 0 deletions src/main/nest/global/decorator/api-update-post.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { applyDecorators, UseInterceptors } from '@nestjs/common';
import { AnyFilesInterceptor } from '@nestjs/platform-express';
import { ApiBody, ApiConsumes } from '@nestjs/swagger';
import { UpdatePostRequestDto } from '../dto';

export function ApiUpdatePost() {
return applyDecorators(
UseInterceptors(AnyFilesInterceptor()),
ApiConsumes('multipart/form-data'),
ApiBody({ type: UpdatePostRequestDto }),
);
}
1 change: 1 addition & 0 deletions src/main/nest/global/decorator/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './api-create-post.decorator';
export * from './api-update-post.decorator';
export * from './api-guard.decorator';
export * from './get-user-id.decorator';
1 change: 1 addition & 0 deletions src/main/nest/global/dto/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export * from './response/find-one-post-response.dto';
export * from './request/create-place-request.dto';
export * from './request/create-menu-request.dto';
export * from './request/create-post-request.dto';
export * from './request/update-post-request.dto';
4 changes: 4 additions & 0 deletions src/main/nest/global/dto/request/update-post-request.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { OmitType, PartialType } from '@nestjs/swagger';
import { CreatePostRequestDto } from './create-post-request.dto';

export class UpdatePostRequestDto extends PartialType(OmitType(CreatePostRequestDto, ['placeId'] as const)) {}
16 changes: 12 additions & 4 deletions src/main/nest/global/dto/response/find-one-post-response.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';

class usertest {
class Users {
@ApiProperty({ example: 1 })
id: number;

Expand All @@ -11,7 +11,12 @@ class usertest {
profileImage: string | null;
}

class usertes123t {
class Categories {
@ApiProperty({ example: 'ν•œμ‹' })
name: string;
}

class Places {
@ApiProperty({ example: 1 })
id: number;

Expand All @@ -29,6 +34,9 @@ class usertes123t {

@ApiProperty({ example: 38.19155114124001 })
y: number;

@ApiProperty({ example: 38.19155114124001 })
categories: Categories;
}

export class FindOnePostResponseDto {
Expand Down Expand Up @@ -57,10 +65,10 @@ export class FindOnePostResponseDto {
createdAt: Date;

@ApiProperty()
users: usertest;
users: Users;

@ApiProperty()
places: usertes123t;
places: Places;

@ApiProperty({ example: 4.5 })
starRatings: number;
Expand Down
3 changes: 3 additions & 0 deletions src/main/nest/global/prisma/prisma.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ export class PrismaService extends PrismaClient implements OnModuleInit, OnModul
if (fields.includes('updatedAt')) {
params.args.data.updatedAt = kstTime;
}
if (fields.includes('deletedAt') && params.args.data.deletedAt !== undefined) {
params.args.data.deletedAt = kstTime;
}
}
return next(params);
});
Expand Down
Loading
Loading