comments 모듈 생성
CLI로 모듈 / 컨트롤러 / 서비스 생성
nest g mo comments
nest g co comments
nest g s comments
JavaScript
복사
기본 세팅 확인
•
commentsModule
•
commentsService
•
commentsController
commentsController 추가 세팅
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { CommentsService } from '../services/comments.service';
import { ApiOperation } from '@nestjs/swagger';
import { CommentsCreateDTO } from '../dto/req/comments.create.dto';
@Controller('comments')
export class CommentsController {
constructor(private readonly commentsService: CommentsService) {}
@ApiOperation({ summary: '모든 고양이 프로필 댓글 가져오기' })
@Get()
async getAllComments() {
return this.commentsService.getAllComments();
}
@ApiOperation({ summary: '특정 고양이 프로필에 댓글 달기' })
@Post(':id')
async createComments(
@Param('id') id: string,
@Body() body: CommentsCreateDTO,
) {
return this.commentsService.createComments(id, body);
}
}
JavaScript
복사
commentsService 추가 세팅
import { CommentsCreateDTO } from '../dto/req/comments.create.dto';
import { Injectable } from '@nestjs/common';
@Injectable()
export class CommentsService {
// 고양이 댓글 생성
createComments(id: string, comments: CommentsCreateDTO) {
return 'Hello world';
}
// 모든 댓글 불러오기
getAllComments() {
return 'Hello world';
}
}
JavaScript
복사
commentsSchema 세팅
import { Prop, Schema, SchemaFactory, SchemaOptions } from '@nestjs/mongoose';
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsPositive, IsString } from 'class-validator';
import { Document, Types } from 'mongoose';
const options: SchemaOptions = {
timestamps: true,
};
@Schema(options)
export class Comments extends Document {
@ApiProperty({
description: '작성한 고양이 id',
required: true,
})
@Prop({
type: Types.ObjectId,
required: true,
ref: 'cats',
})
@IsNotEmpty()
author: Types.ObjectId;
@ApiProperty({
description: '댓글 컨텐츠',
required: true,
})
@Prop({
required: true,
})
@IsNotEmpty()
@IsString()
contents: string;
@ApiProperty({
description: '좋아요 수',
})
@Prop({
default: 0,
required: true,
})
@IsNotEmpty()
@IsPositive()
likeCount: number;
@ApiProperty({
description: '작성 대상 (게시물, 정보글)',
required: true,
})
@Prop({
type: Types.ObjectId,
required: true,
ref: 'cats',
})
@IsNotEmpty()
info: Types.ObjectId;
}
export const CommentsSchema = SchemaFactory.createForClass(Comments);
JavaScript
복사
comments.create.dto
1.
폴더 구조 생성
쓸수록 nestJS 약간 별로 같은데, 일단 요청 dto를 dto>req 폴더로 생성해서 요청DTO를 분리할 계획
2.
정의
import { PickType } from '@nestjs/swagger';
import { Comments } from '../../comments.schema';
export class CommentsCreateDTO extends PickType(Comments, [
'author',
'contents',
] as const) {}
JavaScript
복사
PickType으로 스키마에서 필요한 것만 가져온다.
좋아요 수 올리기 api
commentsController api 생성
@ApiOperation({ summary: '좋아요 수 올리기' })
@Post(':id')
async addLike(@Param('id') id: string) {
return this.commentsService.addLike(id);
}
JavaScript
복사
위의 내용을 컨트롤러에 추가
commentsService내 함수 추가
// 좋아요 추가
addLike(id: string) {}
JavaScript
복사
함수 선언만 하고 로직은 나중에