Refactors API responses and data schemas
Enhances Swagger API documentation by enabling class-validator shim, recognizing entity DTOs, and adding YAML support for raw definitions. Standardizes error handling by transitioning from RxJS's `NotFoundError` to NestJS's `NotFoundException`. Refactors DTOs and Mongoose schemas across the `Article`, `Taxonomy`, and `Content` modules. This includes renaming DTOs for consistency, integrating `class-transformer` for model-to-DTO conversion, and adding `class-validator` for improved schema validation. The `Content` data model is redesigned to be more flexible, shifting from a fixed site header structure to a dynamic key-label-sections model that embeds taxonomy references. This allows for more generic and configurable content retrieval. Updates `Article` and `Taxonomy` services and controllers to fetch specific items by slug or ID and return properly structured DTOs.
This commit is contained in:
1 parent
f77f5f9543
commit
2f027a361b
16 files changed
+279
-201
No files matched your search
+3
-2
@@ -8,9 +8,10 @@
|
||||
{
|
||||
"name": "@nestjs/swagger",
|
||||
"options": {
|
||||
"classValidatorShim": false,
|
||||
"classValidatorShim": true,
|
||||
"introspectComments": true,
|
||||
"skipAutoHttpCode": true
|
||||
"skipAutoHttpCode": true,
|
||||
"dtoFileNameSuffix": [".dto.ts", ".entity.ts"]
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
+2
-1
@@ -24,8 +24,9 @@ import { ArticleModule } from './modules/article/article.module';
|
||||
AccountModule,
|
||||
ImageModule,
|
||||
TaxonomyModule,
|
||||
ContentModule,
|
||||
|
||||
ArticleModule,
|
||||
ContentModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
|
||||
+4
-4
@@ -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);
|
||||
|
||||
@@ -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<TaxonomyPath[] | null> {
|
||||
): Promise<GetTaxonomyPathResponseDto> {
|
||||
return this.articleService.getTaxonomyPathsBySlug(slug);
|
||||
}
|
||||
|
||||
@Get(':slug')
|
||||
@ApiOkResponse({ type: GetArticleResponseDto })
|
||||
getArticle(@Param('slug') slug: string): Promise<GetArticleResponseDto> {
|
||||
return this.articleService.getArticle(slug);
|
||||
}
|
||||
|
||||
@@ -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<TaxonomyPath[] | null> {
|
||||
async getTaxonomyPathsBySlug(slug: string): Promise<GetTaxonomyPathResponseDto> {
|
||||
// 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]);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+6
-3
@@ -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 })
|
||||
@@ -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<GetSiteHeaderResponseDto[]> {
|
||||
return this.contentService.getSiteHeader()
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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<GetSiteHeaderResponseDto[]> {
|
||||
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, {
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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: 'Learn' })
|
||||
displayName: string;
|
||||
@ApiProperty({ example: 'getting-started' })
|
||||
label: string;
|
||||
}
|
||||
export class ContentSectionDto {
|
||||
@ApiProperty({ example: '시작하기' })
|
||||
headline: 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;
|
||||
}
|
||||
@@ -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<mongoose.Types.ObjectId>,
|
||||
MongooseTimestamps {
|
||||
extends MongooseTimestamps {
|
||||
label: string;
|
||||
items: TaxonomyChildItem[];
|
||||
metadatas: Metadata[];
|
||||
}
|
||||
|
||||
export type TaxonomyDocument = HydratedDocument<Taxonomy>
|
||||
|
||||
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<mongoose.Types.ObjectId>,
|
||||
MongooseTimestamps {
|
||||
extends MongooseTimestamps {
|
||||
key: string;
|
||||
label: string;
|
||||
sections: ContentSection[];
|
||||
}
|
||||
|
||||
export type ContentDocument = HydratedDocument<Content>
|
||||
|
||||
export interface Article
|
||||
extends Document<mongoose.Types.ObjectId>,
|
||||
MongooseTimestamps {
|
||||
extends MongooseTimestamps {
|
||||
title: string;
|
||||
slug: string;
|
||||
content: string;
|
||||
@@ -52,6 +58,8 @@ export interface Article
|
||||
metadatas: Metadata[];
|
||||
}
|
||||
|
||||
export type ArticleDocument = HydratedDocument<Article>
|
||||
|
||||
export const MetadataSubSchema = new mongoose.Schema<Metadata>({
|
||||
key: { type: String, required: true },
|
||||
value: {
|
||||
@@ -59,27 +67,29 @@ export const MetadataSubSchema = new mongoose.Schema<Metadata>({
|
||||
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<TaxonomyChildItem>(
|
||||
{
|
||||
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<Taxonomy>(
|
||||
{
|
||||
// items 배열은 위에서 정의한 재귀 스키마를 따름
|
||||
label: { type: String, required: true },
|
||||
items: {
|
||||
type: [TaxonomyChildItemSchema],
|
||||
type: [TaxonomyChildItemSubSchema],
|
||||
default: [],
|
||||
},
|
||||
|
||||
@@ -112,12 +122,34 @@ 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: 'Duplicate metadata keys are not allowed.',
|
||||
message: function (props: any) {
|
||||
const dataType = (this as Metadata).dataType;
|
||||
return `Value "${props.value}" does not match the expected data type "${dataType}".`;
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -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<ContentSectionEmbeddedTaxonomy>(
|
||||
{
|
||||
taxonomyId: { type: Schema.Types.ObjectId, ref: 'taxonomy', required: true },
|
||||
label: { type: String, required: true },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
export const ContentSectionSubSchema = new Schema<ContentSection>(
|
||||
{
|
||||
headline: { type: String, required: true },
|
||||
taxonomies: {
|
||||
type: [ContentSectionEmbeddedTaxonomySubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
export const ContentSchema = new Schema<Content>(
|
||||
{
|
||||
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<Article>(
|
||||
{
|
||||
title: { type: String, required: true },
|
||||
content: { type: String, required: true },
|
||||
|
||||
@@ -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[];
|
||||
|
||||
@@ -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<GetChildResponseDto> {
|
||||
return this.taxonomyService.getChildItems();
|
||||
@ApiOkResponse({ type: GetChildItemResponseDto })
|
||||
getChildItems(@Param('id') taxonomyId: string): Promise<GetChildItemResponseDto> {
|
||||
return this.taxonomyService.getChildItems(taxonomyId);
|
||||
}
|
||||
}
|
||||
@@ -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<GetChildResponseDto> {
|
||||
public async getChildItems(taxonomyId: string): Promise<GetChildItemResponseDto> {
|
||||
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, {});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user