diff --git a/nest-cli.json b/nest-cli.json index ec3a362..9083d2f 100644 --- a/nest-cli.json +++ b/nest-cli.json @@ -8,9 +8,10 @@ { "name": "@nestjs/swagger", "options": { - "classValidatorShim": false, + "classValidatorShim": true, "introspectComments": true, - "skipAutoHttpCode": true + "skipAutoHttpCode": true, + "dtoFileNameSuffix": [".dto.ts", ".entity.ts"] } } ] diff --git a/src/app.module.ts b/src/app.module.ts index 9efe498..b789cf1 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -24,8 +24,9 @@ import { ArticleModule } from './modules/article/article.module'; AccountModule, ImageModule, TaxonomyModule, - ContentModule, + ArticleModule, + ContentModule, ], controllers: [AppController], providers: [AppService], diff --git a/src/main.ts b/src/main.ts index 8500494..cc6512e 100644 --- a/src/main.ts +++ b/src/main.ts @@ -18,13 +18,13 @@ async function bootstrap() { .setVersion('1.0') .addTag('moeum') .addServer(`https://moeum.dahyeon.us/`) - .addBearerAuth({ - type: 'openIdConnect', - }) + // .addBearerAuth({ + // type: 'openIdConnect', + // }) .build(); const options: SwaggerCustomOptions = { ui: true, - raw: ['json'], + raw: ['json', 'yaml'], }; const documentFactory = () => SwaggerModule.createDocument(app, config); SwaggerModule.setup(`v${apiVersion}/api`, app, documentFactory, options); diff --git a/src/modules/article/article.controller.ts b/src/modules/article/article.controller.ts index fd563bb..7e22884 100644 --- a/src/modules/article/article.controller.ts +++ b/src/modules/article/article.controller.ts @@ -1,20 +1,22 @@ import { Controller, Get, Param } from '@nestjs/common'; -import { GetArticleResponseDto } from './dto/get-article-response-dto'; +import { GetArticleResponseDto } from './dto/get-article-response.dto'; import { ArticleService, TaxonomyPath } from './article.service.js'; -import { TaxonomyPathDto } from './dto/get-taxonomy-path-dto'; - +import { ApiOkResponse } from '@nestjs/swagger'; +import { GetTaxonomyPathResponseDto } from './dto/get-taxonomy-path.dto'; @Controller('articles') export class ArticleController { constructor(private readonly articleService: ArticleService) {} @Get(':slug/taxonomy-path') + @ApiOkResponse({ type: GetTaxonomyPathResponseDto }) getArticleTaxonomyPath( @Param('slug') slug: string, - ): Promise { + ): Promise { return this.articleService.getTaxonomyPathsBySlug(slug); } @Get(':slug') + @ApiOkResponse({ type: GetArticleResponseDto }) getArticle(@Param('slug') slug: string): Promise { return this.articleService.getArticle(slug); } diff --git a/src/modules/article/article.service.ts b/src/modules/article/article.service.ts index 23776a7..c4a942a 100644 --- a/src/modules/article/article.service.ts +++ b/src/modules/article/article.service.ts @@ -1,9 +1,10 @@ -import { Injectable } from '@nestjs/common'; +import { Injectable, NotFoundException } from '@nestjs/common'; import { ConnectionService } from '../global/database/connection.service'; -import { GetArticleResponseDto } from './dto/get-article-response-dto'; -import { NotFoundError } from 'rxjs'; +import { GetArticleResponseDto } from './dto/get-article-response.dto'; import { TaxonomyChildItem } from '../global/database/schema'; import mongoose from 'mongoose'; +import { GetTaxonomyPathResponseDto } from './dto/get-taxonomy-path.dto'; +import { plainToInstance } from 'class-transformer'; export interface TaxonomyPathItem { title: string; @@ -33,7 +34,7 @@ export class ArticleService { // response?.slug if (!response) { - throw new NotFoundError('Article not found'); + throw new NotFoundException('Article not found'); } const dto: GetArticleResponseDto = { @@ -76,7 +77,7 @@ export class ArticleService { return results; } - async getTaxonomyPathsBySlug(slug: string): Promise { + async getTaxonomyPathsBySlug(slug: string): Promise { // 1) Article 찾기 const articleModel = await this.connectionService.getMoeumModels('article'); const taxonomyModel = @@ -84,7 +85,7 @@ export class ArticleService { const article = await articleModel.findOne({ slug }).lean().exec(); if (!article) { - return null; + throw new NotFoundException('Article not found'); } const articleId = article._id as unknown as mongoose.Types.ObjectId; @@ -112,13 +113,13 @@ export class ArticleService { for (const p of pathsInThisTaxonomy) { paths.push({ - taxonomyId: taxonomy._id as any, + taxonomyId: taxonomy._id, taxonomyLabel: taxonomy.label, items: p, }); } } - return paths; + return plainToInstance(GetTaxonomyPathResponseDto, paths[0]); } } diff --git a/src/modules/article/dto/get-article-response-dto.ts b/src/modules/article/dto/get-article-response-dto.ts deleted file mode 100644 index 5870b0b..0000000 --- a/src/modules/article/dto/get-article-response-dto.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { ApiProperty } from '@nestjs/swagger'; - -export class GetArticleMetadataDto { - @ApiProperty({ type: String }) - key: string; - - @ApiProperty({ type: 'string', nullable: true, isArray: true }) - value: string | any[] | null; - - @ApiProperty({ type: String }) - dataType: string; - - @ApiProperty({ type: Boolean }) - isReserved: boolean; -} - -export class GetArticleResponseDto { - @ApiProperty({ type: String }) - _id!: string; - - @ApiProperty({ type: String }) - title!: string; - - @ApiProperty({ type: String }) - slug!: string; - - @ApiProperty({ type: String }) - content!: string; - - @ApiProperty({ type: String, enum: ['draft', 'published', 'archived'] }) - status!: 'draft' | 'published' | 'archived'; - - @ApiProperty({ type: [GetArticleMetadataDto] }) - metadatas!: GetArticleMetadataDto[]; - - @ApiProperty({ type: String, format: 'date-time' }) - createdAt!: Date; - - @ApiProperty({ type: String, format: 'date-time' }) - updatedAt!: Date; -} diff --git a/src/modules/article/dto/get-article-response.dto.ts b/src/modules/article/dto/get-article-response.dto.ts new file mode 100644 index 0000000..9e8268d --- /dev/null +++ b/src/modules/article/dto/get-article-response.dto.ts @@ -0,0 +1,56 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsBoolean, IsIn, IsOptional, IsString, ValidateIf } from 'class-validator'; + +export class ArticleMetadataDto { + @ApiProperty({ example: 'category' }) + @IsString() + key!: string; + + // string | any[] | null 이지만, API 레벨에서는 string[] 정도로 제한하는 것도 고려 가능 + @ApiProperty({ + oneOf: [ + { type: 'string' }, + { type: 'array', items: { type: 'string' } }, + ], + }) + @ValidateIf((o) => o.value !== undefined) + value!: string | string[] + + @ApiProperty({ + enum: ['string', 'number', 'boolean', 'array', 'json'], + default: 'string', + }) + @IsIn(['string', 'number', 'boolean', 'array', 'json']) + dataType!: 'string' | 'number' | 'boolean' | 'array' | 'json'; + + @ApiProperty({ default: false }) + @IsBoolean() + @IsOptional() + isReserved?: boolean; +} + +export class GetArticleResponseDto { + @ApiProperty({ type: String }) + _id!: string; + + @ApiProperty({ type: String }) + title!: string; + + @ApiProperty({ type: String }) + slug!: string; + + @ApiProperty({ type: String }) + content!: string; + + @ApiProperty({ type: String, enum: ['draft', 'published', 'archived'] }) + status!: 'draft' | 'published' | 'archived'; + + @ApiProperty({ type: [ArticleMetadataDto] }) + metadatas!: ArticleMetadataDto[]; + + @ApiProperty({ type: String, format: 'date-time' }) + createdAt!: Date; + + @ApiProperty({ type: String, format: 'date-time' }) + updatedAt!: Date; +} diff --git a/src/modules/article/dto/get-taxonomy-path-dto.ts b/src/modules/article/dto/get-taxonomy-path.dto.ts similarity index 62% rename from src/modules/article/dto/get-taxonomy-path-dto.ts rename to src/modules/article/dto/get-taxonomy-path.dto.ts index 2e19b0e..fb7ac06 100644 --- a/src/modules/article/dto/get-taxonomy-path-dto.ts +++ b/src/modules/article/dto/get-taxonomy-path.dto.ts @@ -1,4 +1,5 @@ import { ApiProperty } from '@nestjs/swagger'; +import { Transform } from 'class-transformer'; export class TaxonomyPathItemDto { @ApiProperty({ type: String }) @@ -7,15 +8,17 @@ export class TaxonomyPathItemDto { @ApiProperty({ type: String, required: false }) slug?: string; - @ApiProperty({ type: String, required: false }) + @ApiProperty({ example: '664fe1c3c2c1e7...' }) + @Transform(({ value }) => value.toString()) articleId?: string; @ApiProperty({ type: Number }) order: number; } -export class TaxonomyPathDto { - @ApiProperty({ type: String }) +export class GetTaxonomyPathResponseDto { + @ApiProperty({ example: '664fe1c3c2c1e7...' }) + @Transform(({ value }) => value.toString()) taxonomyId: string; @ApiProperty({ type: String }) diff --git a/src/modules/content/content.controler.ts b/src/modules/content/content.controler.ts index 5b01d80..2fca514 100644 --- a/src/modules/content/content.controler.ts +++ b/src/modules/content/content.controler.ts @@ -1,9 +1,18 @@ -import { Controller, Get } from '@nestjs/common'; +import { Controller, Get, Param } from '@nestjs/common'; +import { GetSiteHeaderResponseDto } from './dto/get-site-header-response.dto'; +import { ContentService } from './content.service'; +import { ApiOkResponse } from '@nestjs/swagger'; @Controller('contents') export class ContentController { + constructor( + private readonly contentService: ContentService + ) {} + + @Get('site-header') - getSiteHeader(): string { - return 'Site Header Content'; + @ApiOkResponse({ type: [GetSiteHeaderResponseDto] }) + getSiteHeaders(): Promise { + return this.contentService.getSiteHeader() } } diff --git a/src/modules/content/content.module.ts b/src/modules/content/content.module.ts index f941ac8..b4da18c 100644 --- a/src/modules/content/content.module.ts +++ b/src/modules/content/content.module.ts @@ -1,7 +1,10 @@ import { Module } from '@nestjs/common'; +import { ContentController } from './content.controler'; +import { ContentService } from './content.service'; @Module({ - controllers: [], - providers: [], + imports: [], + controllers: [ContentController], + providers: [ContentService], }) export class ContentModule {} diff --git a/src/modules/content/content.service.ts b/src/modules/content/content.service.ts index d8093a0..d509190 100644 --- a/src/modules/content/content.service.ts +++ b/src/modules/content/content.service.ts @@ -1,4 +1,33 @@ -import { Injectable } from '@nestjs/common'; +import { Injectable, NotFoundException } from '@nestjs/common'; +import { ConnectionService } from '../global/database/connection.service'; +import { GetSiteHeaderResponseDto } from './dto/get-site-header-response.dto'; +import { plainToInstance } from 'class-transformer'; @Injectable() -export class ContentService {} +export class ContentService { + constructor( + private readonly connectionService: ConnectionService + ) {} + + async getSiteHeader(): Promise { + const contentModel = await this.connectionService.getMoeumModels('content') + + const document = await contentModel.find({}, { + _id: 0, + createdAt: 0, + updatedAt: 0, + __v: 0 + }).lean() + + if (!document) { + throw new NotFoundException("Content Not Found") + } + console.log(document) + + + return plainToInstance(GetSiteHeaderResponseDto, document, { + + }); + + } +} diff --git a/src/modules/content/dto/get-site-header-response.dto.ts b/src/modules/content/dto/get-site-header-response.dto.ts index 2043c08..0c41f9e 100644 --- a/src/modules/content/dto/get-site-header-response.dto.ts +++ b/src/modules/content/dto/get-site-header-response.dto.ts @@ -1,96 +1,35 @@ import { ApiProperty } from '@nestjs/swagger'; +import { Transform, Type } from 'class-transformer'; +import mongoose from 'mongoose'; -// 1. 하위 객체 정의 (BrandLink) -export class BrandLinkDto { - @ApiProperty({ example: 'learn' }) - biName: string; +export class ContentSectionEmbeddedTaxonomyDto { + @ApiProperty({ example: '664fe1c3c2c1e7...' }) + @Transform(({ value }) => value.toString()) + taxonomyId: string; + + @ApiProperty({ example: 'getting-started' }) + label: string; +} +export class ContentSectionDto { + @ApiProperty({ example: '시작하기' }) + headline: string; - @ApiProperty({ example: 'Learn' }) - displayName: string; - - @ApiProperty({ example: '/' }) - href: string; + @ApiProperty({ type: [ContentSectionEmbeddedTaxonomyDto], example: [{ + "taxonomyId": "6916d575eaa6f7c53096e348", + "label": "Top Stories" + }] }) + taxonomies: ContentSectionEmbeddedTaxonomyDto[]; } -// 2. 하위 객체 정의 (FeaturedContent) -export class FeaturedContentDto { - @ApiProperty({ example: '1-ai-tour' }) - biName: string; - - @ApiProperty({ example: 'Take your business to the AI frontier.' }) - description: string; - - @ApiProperty({ example: 'https://aitour.microsoft.com/...' }) - href: string; - - @ApiProperty({ example: 'Free to join. Request to attend.' }) - supertitle: string; - - @ApiProperty({ example: 'Microsoft AI Tour' }) - title: string; -} - -// 3. 하위 객체 정의 (Metadata) -export class MetadataDto { - @ApiProperty({ example: 'baf032e20e264014dcc89b0e0b0333c96293ecd7' }) - version: string; -} - -// 4. 하위 객체 정의 (PanelContent) -// NavCategories 내부의 실제 링크 아이템들 -export class PanelContentItemDto { - @ApiProperty({ example: '1-documentation' }) - biName: string; - - @ApiProperty({ example: 'header-panel-link' }) - componentType: string; - - @ApiProperty({ example: '/docs/' }) - href: string; - - @ApiProperty({ example: 'All product documentation' }) - title: string; - - // Topics 패널에는 description이 있지만 다른 곳에는 없을 수 있으므로 옵셔널 처리 - @ApiProperty({ required: false, example: 'Learning hub to build AI skills' }) - description?: string; -} - -// 5. 하위 객체 정의 (Panel) -export class PanelDto { - @ApiProperty({ type: [PanelContentItemDto] }) - panelContent: PanelContentItemDto[]; -} - -// 6. 하위 객체 정의 (NavCategory) -export class NavCategoryDto { - @ApiProperty({ example: '1-documentation' }) - biName: string; - - @ApiProperty({ type: PanelDto }) - panel: PanelDto; - - @ApiProperty({ example: 'Documentation' }) - title: string; -} - -// 7. 메인 DTO (Response DTO) export class GetSiteHeaderResponseDto { - @ApiProperty({ type: BrandLinkDto }) - brandLink: BrandLinkDto; + @ApiProperty({ example: 'home' }) + key: string; - @ApiProperty({ type: [FeaturedContentDto] }) - featuredContent: FeaturedContentDto[]; + @ApiProperty({ example: 'Home' }) + label: string; - @ApiProperty({ type: MetadataDto }) - metadata: MetadataDto; + @ApiProperty({ type: [ContentSectionDto] }) + sections: ContentSectionDto[]; - @ApiProperty({ type: [NavCategoryDto] }) - navCategories: NavCategoryDto[]; - - @ApiProperty({ example: 'SiteHeader' }) - schema: string; - - @ApiProperty({ example: 'content-header' }) - type: string; + } diff --git a/src/modules/global/database/schema.ts b/src/modules/global/database/schema.ts index 6057ec8..28340ee 100644 --- a/src/modules/global/database/schema.ts +++ b/src/modules/global/database/schema.ts @@ -1,4 +1,4 @@ -import mongoose, { Schema, Document } from 'mongoose'; +import mongoose, { Schema, Document, HydratedDocument } from 'mongoose'; import { ModelDefinition } from './types'; export interface MongooseTimestamps { @@ -8,8 +8,8 @@ export interface MongooseTimestamps { export interface Metadata { key: string; - value: string | any[] | null; - dataType: string; + value: string | any[] + dataType: 'string' | 'number' | 'boolean' | 'array' | 'json'; isReserved: boolean; } @@ -22,29 +22,35 @@ export interface TaxonomyChildItem { } export interface Taxonomy - extends Document, - MongooseTimestamps { + extends MongooseTimestamps { label: string; items: TaxonomyChildItem[]; metadatas: Metadata[]; } +export type TaxonomyDocument = HydratedDocument + export interface ContentSection { - heading: string; - taxonomies: mongoose.Types.ObjectId[]; + headline: string; + taxonomies: ContentSectionEmbeddedTaxonomy[]; +} + +export interface ContentSectionEmbeddedTaxonomy { + taxonomyId: mongoose.Types.ObjectId; + label: string; // 성능 최적화를 위해 임베딩된 label } export interface Content - extends Document, - MongooseTimestamps { + extends MongooseTimestamps { key: string; label: string; sections: ContentSection[]; } +export type ContentDocument = HydratedDocument + export interface Article - extends Document, - MongooseTimestamps { + extends MongooseTimestamps { title: string; slug: string; content: string; @@ -52,6 +58,8 @@ export interface Article metadatas: Metadata[]; } +export type ArticleDocument = HydratedDocument
+ export const MetadataSubSchema = new mongoose.Schema({ key: { type: String, required: true }, value: { @@ -59,27 +67,29 @@ export const MetadataSubSchema = new mongoose.Schema({ required: false, // required: true로 하면 value가 null인 경우 에러 발생 default: null, validate: { - validator: function (v: string | any[] | null) { + validator: function (v: string | any[]) { // 특정 키인 경우 value가 null 또는 빈 문자열이 아니어야 함 // if (this.key === 'requiredKey') { // return typeof v === 'string' && v.trim().length > 0; // } // 그렇지 않은 경우 value는 null 또는 문자열, Array이어야 함 - return v === null || typeof v === 'string' || Array.isArray(v); + return typeof v === 'string' || Array.isArray(v); }, message: function (props: any) { if (this.key === 'requiredKey') { return `Value is required for key "${this.key}" and cannot be null or empty.`; } - return `Value must be a string, an array, or null for key "${this.key}".`; + return `Value must be a string or array for key "${this.key}".`; }, }, }, - dataType: { type: String, required: false, default: 'string' }, + dataType: { type: String, required: false, default: 'string', enum: ['string', 'number', 'boolean', 'array', 'json'] }, isReserved: { type: Boolean, required: false, default: false }, +}, { + _id: false, }); -export const TaxonomyChildItemSchema = new Schema( +export const TaxonomyChildItemSubSchema = new Schema( { title: { type: String, required: true }, order: { type: Number, required: true, default: 100 }, @@ -93,17 +103,17 @@ export const TaxonomyChildItemSchema = new Schema( // **중요: 재귀 참조 설정** // 스키마 정의 후 .add()를 통해 자기 자신을 children 배열로 추가합니다. -TaxonomyChildItemSchema.add({ - children: { type: [TaxonomyChildItemSchema], default: [] }, +TaxonomyChildItemSubSchema.add({ + children: { type: [TaxonomyChildItemSubSchema], default: [] }, }); // 2. 메인 도큐먼트 스키마 (Root) -export const TaxonomySchema = new Schema( +export const TaxonomySchema = new Schema( { // items 배열은 위에서 정의한 재귀 스키마를 따름 label: { type: String, required: true }, items: { - type: [TaxonomyChildItemSchema], + type: [TaxonomyChildItemSubSchema], default: [], }, @@ -112,13 +122,35 @@ export const TaxonomySchema = new Schema( type: [MetadataSubSchema], required: true, default: [], - validate: { - validator: function (metas: Metadata[]) { - const keys = metas.map((m) => m.key); - return keys.length === new Set(keys).size; + validator: function (v: string | any[] | number | boolean | object | null) { + // 'this'는 현재 검증 중인 Metadata 서브 도큐먼트를 가리킵니다. + const dataType = (this as Metadata).dataType; + + if (v === null) { + return true; // null은 항상 허용 (required: false이므로) + } + + switch (dataType) { + case 'string': + return typeof v === 'string'; + case 'number': + return typeof v === 'number'; + case 'boolean': + return typeof v === 'boolean'; + case 'array': + return Array.isArray(v); + case 'json': + // JSON은 객체 형태일 수 있습니다. + return typeof v === 'object' && v !== null && !Array.isArray(v); + default: + // 'string'이 기본값이므로 이쪽으로 빠지는 경우는 드물지만, 방어 코드 + return typeof v === 'string'; + } + }, + message: function (props: any) { + const dataType = (this as Metadata).dataType; + return `Value "${props.value}" does not match the expected data type "${dataType}".`; }, - message: 'Duplicate metadata keys are not allowed.', - }, }, }, { @@ -129,16 +161,34 @@ export const TaxonomySchema = new Schema( TaxonomySchema.index({ label: 1 }, { unique: true }); -export const ContentSchema = new Schema( +export const ContentSectionEmbeddedTaxonomySubSchema = new Schema( + { + taxonomyId: { type: Schema.Types.ObjectId, ref: 'taxonomy', required: true }, + label: { type: String, required: true }, + }, + { _id: false }, +); + +export const ContentSectionSubSchema = new Schema( + { + headline: { type: String, required: true }, + taxonomies: { + type: [ContentSectionEmbeddedTaxonomySubSchema], + required: true, + default: [], + }, + }, + { _id: false }, +); + +export const ContentSchema = new Schema( { key: { type: String, required: true, unique: true }, label: { type: String, required: true }, sections: { + type: [ - { - heading: { type: String, required: true }, - taxonomies: [{ type: Schema.Types.ObjectId, ref: 'taxonomy' }], - }, + ContentSectionSubSchema ], default: [], }, @@ -149,7 +199,7 @@ export const ContentSchema = new Schema( }, ); -export const ArticleSchema = new Schema( +export const ArticleSchema = new Schema
( { title: { type: String, required: true }, content: { type: String, required: true }, diff --git a/src/modules/taxonomy/dto/get-child-item.dto.ts b/src/modules/taxonomy/dto/get-child-item.dto.ts index c6fb998..df63004 100644 --- a/src/modules/taxonomy/dto/get-child-item.dto.ts +++ b/src/modules/taxonomy/dto/get-child-item.dto.ts @@ -1,5 +1,6 @@ import { ApiProperty } from '@nestjs/swagger'; -import { Expose, Type } from 'class-transformer'; +import { Expose, Transform, Type } from 'class-transformer'; +import { Types } from 'mongoose'; export class GetChildItemMetadataDto {} @@ -7,8 +8,19 @@ export class GetChildItemDto { @ApiProperty({ example: 'Install' }) title: string; - @ApiProperty({ required: false, example: 'install' }) - href?: string; + @ApiProperty({ example: 100 }) + order: number; + + @ApiProperty({ required: false, example: 'new-ai-model-achieves-milestone' }) + slug?: string; + + @ApiProperty({ required: false, example: '664fe1c3c2c1e7...' }) + @Transform(({ value }) => { + if (value == null) return undefined; + if (value instanceof Types.ObjectId) return value.toString(); + return String(value); // 이미 string이어도 그냥 통과 + }, { toPlainOnly: true }) + articleId?: string; // 재귀적으로 자기 자신(GetChildItemDto)을 리스트로 가질 수 있음을 명시 @ApiProperty({ @@ -21,7 +33,10 @@ export class GetChildItemDto { } // 3. 전체 응답 DTO (Root) -export class GetChildResponseDto { +export class GetChildItemResponseDto { + @ApiProperty({ type: String }) + label: string; + @ApiProperty({ type: [GetChildItemDto] }) @Type(() => GetChildItemDto) items: GetChildItemDto[]; diff --git a/src/modules/taxonomy/taxonomy.controller.ts b/src/modules/taxonomy/taxonomy.controller.ts index 55226e5..d954b5c 100644 --- a/src/modules/taxonomy/taxonomy.controller.ts +++ b/src/modules/taxonomy/taxonomy.controller.ts @@ -1,13 +1,15 @@ -import { Controller, Get } from '@nestjs/common'; +import { Controller, Get, Param } from '@nestjs/common'; import { TaxonomyService } from './taxonomy.service'; -import { GetChildResponseDto } from './dto/get-child-item.dto'; +import { GetChildItemResponseDto } from './dto/get-child-item.dto'; +import { ApiOkResponse } from '@nestjs/swagger'; @Controller('taxonomies') export class TaxonomyController { constructor(private readonly taxonomyService: TaxonomyService) {} @Get(':id/child-items') - getChildItems(): Promise { - return this.taxonomyService.getChildItems(); + @ApiOkResponse({ type: GetChildItemResponseDto }) + getChildItems(@Param('id') taxonomyId: string): Promise { + return this.taxonomyService.getChildItems(taxonomyId); } } diff --git a/src/modules/taxonomy/taxonomy.service.ts b/src/modules/taxonomy/taxonomy.service.ts index 440fd06..41e464f 100644 --- a/src/modules/taxonomy/taxonomy.service.ts +++ b/src/modules/taxonomy/taxonomy.service.ts @@ -1,19 +1,27 @@ -import { Injectable } from '@nestjs/common'; +import { Injectable, NotFoundException } from '@nestjs/common'; import { ConnectionService } from '../global/database/connection.service'; -import { GetChildResponseDto } from './dto/get-child-item.dto'; -import { NotFoundError } from 'rxjs'; +import { GetChildItemResponseDto } from './dto/get-child-item.dto'; +import { plainToInstance } from 'class-transformer'; @Injectable() export class TaxonomyService { constructor(private readonly connectionService: ConnectionService) {} - public async getChildItems(): Promise { + public async getChildItems(taxonomyId: string): Promise { const taxonomyModel = await this.connectionService.getMoeumModels('taxonomy'); - const response = await taxonomyModel.findOne().lean(); - if (!response) { - throw new NotFoundError('No taxonomy found'); + const document = await taxonomyModel.findOne({ + _id: taxonomyId, + }, { + label: 1, + items: 1, + metadatas: 1 + }).lean() + if (!document) { + throw new NotFoundException('No taxonomy found'); } - return response; + + // return document + return plainToInstance(GetChildItemResponseDto, document, {}); } }