11import {
22 BadRequestException ,
3+ ConflictException ,
34 ForbiddenException ,
45 Injectable ,
56 NotFoundException ,
67} from '@nestjs/common' ;
7- import { DataSource , EntityManager } from 'typeorm' ;
8+ import { DataSource , EntityManager , In , Not } from 'typeorm' ;
89
910import {
1011 AddContentBodyDto ,
@@ -184,8 +185,6 @@ export class ContentsService {
184185 reminder,
185186 favorite,
186187 categoryId,
187- categoryName,
188- parentId,
189188 } : UpdateContentBodyDto ,
190189 entityManager ?: EntityManager ,
191190 ) : Promise < AddContentOutput > {
@@ -197,32 +196,41 @@ export class ContentsService {
197196 reminder,
198197 favorite,
199198 } ;
200- const userInDb = await this . userRepository . findOneWithContentsAndCategories (
201- user . id ,
202- ) ;
203- if ( ! userInDb ) {
204- throw new NotFoundException ( 'User not found' ) ;
205- }
206199
207- const content = userInDb ?. contents ?. filter (
208- ( content ) => content . id === contentId ,
209- ) [ 0 ] ;
200+ const content = await this . contentRepository . findOne ( {
201+ where : {
202+ id : contentId ,
203+ } ,
204+ relations : [ 'category' ] ,
205+ } ) ;
206+
210207 if ( ! content ) {
211- throw new NotFoundException ( 'Content not found .' ) ;
208+ throw new NotFoundException ( '컨텐츠가 존재하지 않습니다 .' ) ;
212209 }
213210
214- if ( categoryId !== undefined ) {
215- const category =
216- categoryId !== null
217- ? await this . categoryRepository . findById ( categoryId , entityManager )
218- : null ;
211+ // 카테고리 변경이 발생하는 경우
212+ if ( categoryId && ! content . isSameCategory ( categoryId ) ) {
213+ const [ category , subCategories ] = await Promise . all ( [
214+ ( async ( ) => {
215+ const category = await this . categoryRepository . findById ( categoryId ) ;
219216
220- if ( category ) {
221- await checkContentDuplicateAndAddCategorySaveLog (
222- link ,
223- category ,
224- userInDb ,
225- ) ;
217+ if ( ! category ) {
218+ throw new NotFoundException ( '카테고리가 존재하지 않습니다.' ) ;
219+ }
220+
221+ return category ;
222+ } ) ( ) ,
223+ this . categoryRepository . findByParentId ( categoryId ) ,
224+ ] ) ;
225+
226+ const isDuplicated = await this . isDuplicatedContents (
227+ content . id ,
228+ [ category , ...subCategories ] ,
229+ content . link ,
230+ ) ;
231+
232+ if ( isDuplicated ) {
233+ throw new ConflictException ( '이미 저장된 컨텐츠입니다.' ) ;
226234 }
227235
228236 await this . contentRepository . updateOne (
@@ -471,4 +479,22 @@ export class ContentsService {
471479 throw e ;
472480 }
473481 }
482+
483+ private async isDuplicatedContents (
484+ id : number ,
485+ categories : Category [ ] ,
486+ link : string ,
487+ ) {
488+ const existingContents = await this . contentRepository . find ( {
489+ where : {
490+ id : Not ( id ) ,
491+ category : {
492+ id : In ( categories . map ( ( category ) => category . id ) ) ,
493+ } ,
494+ link,
495+ } ,
496+ } ) ;
497+
498+ return existingContents . length > 0 ;
499+ }
474500}
0 commit comments