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
+280
-202
No files matched your search
+3
-2
@@ -8,9 +8,10 @@
|
|||||||
{
|
{
|
||||||
"name": "@nestjs/swagger",
|
"name": "@nestjs/swagger",
|
||||||
"options": {
|
"options": {
|
||||||
"classValidatorShim": false,
|
"classValidatorShim": true,
|
||||||
"introspectComments": 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,
|
AccountModule,
|
||||||
ImageModule,
|
ImageModule,
|
||||||
TaxonomyModule,
|
TaxonomyModule,
|
||||||
ContentModule,
|
|
||||||
ArticleModule,
|
ArticleModule,
|
||||||
|
ContentModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService],
|
providers: [AppService],
|
||||||
|
|||||||
+4
-4
@@ -18,13 +18,13 @@ async function bootstrap() {
|
|||||||
.setVersion('1.0')
|
.setVersion('1.0')
|
||||||
.addTag('moeum')
|
.addTag('moeum')
|
||||||
.addServer(`https://moeum.dahyeon.us/`)
|
.addServer(`https://moeum.dahyeon.us/`)
|
||||||
.addBearerAuth({
|
// .addBearerAuth({
|
||||||
type: 'openIdConnect',
|
// type: 'openIdConnect',
|
||||||
})
|
// })
|
||||||
.build();
|
.build();
|
||||||
const options: SwaggerCustomOptions = {
|
const options: SwaggerCustomOptions = {
|
||||||
ui: true,
|
ui: true,
|
||||||
raw: ['json'],
|
raw: ['json', 'yaml'],
|
||||||
};
|
};
|
||||||
const documentFactory = () => SwaggerModule.createDocument(app, config);
|
const documentFactory = () => SwaggerModule.createDocument(app, config);
|
||||||
SwaggerModule.setup(`v${apiVersion}/api`, app, documentFactory, options);
|
SwaggerModule.setup(`v${apiVersion}/api`, app, documentFactory, options);
|
||||||
|
|||||||
@@ -1,20 +1,22 @@
|
|||||||
import { Controller, Get, Param } from '@nestjs/common';
|
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 { 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')
|
@Controller('articles')
|
||||||
export class ArticleController {
|
export class ArticleController {
|
||||||
constructor(private readonly articleService: ArticleService) {}
|
constructor(private readonly articleService: ArticleService) {}
|
||||||
|
|
||||||
@Get(':slug/taxonomy-path')
|
@Get(':slug/taxonomy-path')
|
||||||
|
@ApiOkResponse({ type: GetTaxonomyPathResponseDto })
|
||||||
getArticleTaxonomyPath(
|
getArticleTaxonomyPath(
|
||||||
@Param('slug') slug: string,
|
@Param('slug') slug: string,
|
||||||
): Promise<TaxonomyPath[] | null> {
|
): Promise<GetTaxonomyPathResponseDto> {
|
||||||
return this.articleService.getTaxonomyPathsBySlug(slug);
|
return this.articleService.getTaxonomyPathsBySlug(slug);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':slug')
|
@Get(':slug')
|
||||||
|
@ApiOkResponse({ type: GetArticleResponseDto })
|
||||||
getArticle(@Param('slug') slug: string): Promise<GetArticleResponseDto> {
|
getArticle(@Param('slug') slug: string): Promise<GetArticleResponseDto> {
|
||||||
return this.articleService.getArticle(slug);
|
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 { ConnectionService } from '../global/database/connection.service';
|
||||||
import { GetArticleResponseDto } from './dto/get-article-response-dto';
|
import { GetArticleResponseDto } from './dto/get-article-response.dto';
|
||||||
import { NotFoundError } from 'rxjs';
|
|
||||||
import { TaxonomyChildItem } from '../global/database/schema';
|
import { TaxonomyChildItem } from '../global/database/schema';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import { GetTaxonomyPathResponseDto } from './dto/get-taxonomy-path.dto';
|
||||||
|
import { plainToInstance } from 'class-transformer';
|
||||||
|
|
||||||
export interface TaxonomyPathItem {
|
export interface TaxonomyPathItem {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -33,7 +34,7 @@ export class ArticleService {
|
|||||||
// response?.slug
|
// response?.slug
|
||||||
|
|
||||||
if (!response) {
|
if (!response) {
|
||||||
throw new NotFoundError('Article not found');
|
throw new NotFoundException('Article not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const dto: GetArticleResponseDto = {
|
const dto: GetArticleResponseDto = {
|
||||||
@@ -76,7 +77,7 @@ export class ArticleService {
|
|||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTaxonomyPathsBySlug(slug: string): Promise<TaxonomyPath[] | null> {
|
async getTaxonomyPathsBySlug(slug: string): Promise<GetTaxonomyPathResponseDto> {
|
||||||
// 1) Article 찾기
|
// 1) Article 찾기
|
||||||
const articleModel = await this.connectionService.getMoeumModels('article');
|
const articleModel = await this.connectionService.getMoeumModels('article');
|
||||||
const taxonomyModel =
|
const taxonomyModel =
|
||||||
@@ -84,7 +85,7 @@ export class ArticleService {
|
|||||||
|
|
||||||
const article = await articleModel.findOne({ slug }).lean().exec();
|
const article = await articleModel.findOne({ slug }).lean().exec();
|
||||||
if (!article) {
|
if (!article) {
|
||||||
return null;
|
throw new NotFoundException('Article not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const articleId = article._id as unknown as mongoose.Types.ObjectId;
|
const articleId = article._id as unknown as mongoose.Types.ObjectId;
|
||||||
@@ -112,13 +113,13 @@ export class ArticleService {
|
|||||||
|
|
||||||
for (const p of pathsInThisTaxonomy) {
|
for (const p of pathsInThisTaxonomy) {
|
||||||
paths.push({
|
paths.push({
|
||||||
taxonomyId: taxonomy._id as any,
|
taxonomyId: taxonomy._id,
|
||||||
taxonomyLabel: taxonomy.label,
|
taxonomyLabel: taxonomy.label,
|
||||||
items: p,
|
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 { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Transform } from 'class-transformer';
|
||||||
|
|
||||||
export class TaxonomyPathItemDto {
|
export class TaxonomyPathItemDto {
|
||||||
@ApiProperty({ type: String })
|
@ApiProperty({ type: String })
|
||||||
@@ -7,15 +8,17 @@ export class TaxonomyPathItemDto {
|
|||||||
@ApiProperty({ type: String, required: false })
|
@ApiProperty({ type: String, required: false })
|
||||||
slug?: string;
|
slug?: string;
|
||||||
|
|
||||||
@ApiProperty({ type: String, required: false })
|
@ApiProperty({ example: '664fe1c3c2c1e7...' })
|
||||||
|
@Transform(({ value }) => value.toString())
|
||||||
articleId?: string;
|
articleId?: string;
|
||||||
|
|
||||||
@ApiProperty({ type: Number })
|
@ApiProperty({ type: Number })
|
||||||
order: number;
|
order: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class TaxonomyPathDto {
|
export class GetTaxonomyPathResponseDto {
|
||||||
@ApiProperty({ type: String })
|
@ApiProperty({ example: '664fe1c3c2c1e7...' })
|
||||||
|
@Transform(({ value }) => value.toString())
|
||||||
taxonomyId: string;
|
taxonomyId: string;
|
||||||
|
|
||||||
@ApiProperty({ type: 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')
|
@Controller('contents')
|
||||||
export class ContentController {
|
export class ContentController {
|
||||||
|
constructor(
|
||||||
|
private readonly contentService: ContentService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
|
||||||
@Get('site-header')
|
@Get('site-header')
|
||||||
getSiteHeader(): string {
|
@ApiOkResponse({ type: [GetSiteHeaderResponseDto] })
|
||||||
return 'Site Header Content';
|
getSiteHeaders(): Promise<GetSiteHeaderResponseDto[]> {
|
||||||
|
return this.contentService.getSiteHeader()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ContentController } from './content.controler';
|
||||||
|
import { ContentService } from './content.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
controllers: [],
|
imports: [],
|
||||||
providers: [],
|
controllers: [ContentController],
|
||||||
|
providers: [ContentService],
|
||||||
})
|
})
|
||||||
export class ContentModule {}
|
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()
|
@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 { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Transform, Type } from 'class-transformer';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
// 1. 하위 객체 정의 (BrandLink)
|
export class ContentSectionEmbeddedTaxonomyDto {
|
||||||
export class BrandLinkDto {
|
@ApiProperty({ example: '664fe1c3c2c1e7...' })
|
||||||
@ApiProperty({ example: 'learn' })
|
@Transform(({ value }) => value.toString())
|
||||||
biName: string;
|
taxonomyId: string;
|
||||||
|
|
||||||
@ApiProperty({ example: 'Learn' })
|
@ApiProperty({ example: 'getting-started' })
|
||||||
displayName: string;
|
label: string;
|
||||||
|
}
|
||||||
|
export class ContentSectionDto {
|
||||||
|
@ApiProperty({ example: '시작하기' })
|
||||||
|
headline: string;
|
||||||
|
|
||||||
@ApiProperty({ example: '/' })
|
@ApiProperty({ type: [ContentSectionEmbeddedTaxonomyDto], example: [{
|
||||||
href: string;
|
"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 {
|
export class GetSiteHeaderResponseDto {
|
||||||
@ApiProperty({ type: BrandLinkDto })
|
@ApiProperty({ example: 'home' })
|
||||||
brandLink: BrandLinkDto;
|
key: string;
|
||||||
|
|
||||||
@ApiProperty({ type: [FeaturedContentDto] })
|
@ApiProperty({ example: 'Home' })
|
||||||
featuredContent: FeaturedContentDto[];
|
label: string;
|
||||||
|
|
||||||
@ApiProperty({ type: MetadataDto })
|
@ApiProperty({ type: [ContentSectionDto] })
|
||||||
metadata: MetadataDto;
|
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';
|
import { ModelDefinition } from './types';
|
||||||
|
|
||||||
export interface MongooseTimestamps {
|
export interface MongooseTimestamps {
|
||||||
@@ -8,8 +8,8 @@ export interface MongooseTimestamps {
|
|||||||
|
|
||||||
export interface Metadata {
|
export interface Metadata {
|
||||||
key: string;
|
key: string;
|
||||||
value: string | any[] | null;
|
value: string | any[]
|
||||||
dataType: string;
|
dataType: 'string' | 'number' | 'boolean' | 'array' | 'json';
|
||||||
isReserved: boolean;
|
isReserved: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,29 +22,35 @@ export interface TaxonomyChildItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface Taxonomy
|
export interface Taxonomy
|
||||||
extends Document<mongoose.Types.ObjectId>,
|
extends MongooseTimestamps {
|
||||||
MongooseTimestamps {
|
|
||||||
label: string;
|
label: string;
|
||||||
items: TaxonomyChildItem[];
|
items: TaxonomyChildItem[];
|
||||||
metadatas: Metadata[];
|
metadatas: Metadata[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type TaxonomyDocument = HydratedDocument<Taxonomy>
|
||||||
|
|
||||||
export interface ContentSection {
|
export interface ContentSection {
|
||||||
heading: string;
|
headline: string;
|
||||||
taxonomies: mongoose.Types.ObjectId[];
|
taxonomies: ContentSectionEmbeddedTaxonomy[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ContentSectionEmbeddedTaxonomy {
|
||||||
|
taxonomyId: mongoose.Types.ObjectId;
|
||||||
|
label: string; // 성능 최적화를 위해 임베딩된 label
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Content
|
export interface Content
|
||||||
extends Document<mongoose.Types.ObjectId>,
|
extends MongooseTimestamps {
|
||||||
MongooseTimestamps {
|
|
||||||
key: string;
|
key: string;
|
||||||
label: string;
|
label: string;
|
||||||
sections: ContentSection[];
|
sections: ContentSection[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ContentDocument = HydratedDocument<Content>
|
||||||
|
|
||||||
export interface Article
|
export interface Article
|
||||||
extends Document<mongoose.Types.ObjectId>,
|
extends MongooseTimestamps {
|
||||||
MongooseTimestamps {
|
|
||||||
title: string;
|
title: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
content: string;
|
content: string;
|
||||||
@@ -52,6 +58,8 @@ export interface Article
|
|||||||
metadatas: Metadata[];
|
metadatas: Metadata[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ArticleDocument = HydratedDocument<Article>
|
||||||
|
|
||||||
export const MetadataSubSchema = new mongoose.Schema<Metadata>({
|
export const MetadataSubSchema = new mongoose.Schema<Metadata>({
|
||||||
key: { type: String, required: true },
|
key: { type: String, required: true },
|
||||||
value: {
|
value: {
|
||||||
@@ -59,27 +67,29 @@ export const MetadataSubSchema = new mongoose.Schema<Metadata>({
|
|||||||
required: false, // required: true로 하면 value가 null인 경우 에러 발생
|
required: false, // required: true로 하면 value가 null인 경우 에러 발생
|
||||||
default: null,
|
default: null,
|
||||||
validate: {
|
validate: {
|
||||||
validator: function (v: string | any[] | null) {
|
validator: function (v: string | any[]) {
|
||||||
// 특정 키인 경우 value가 null 또는 빈 문자열이 아니어야 함
|
// 특정 키인 경우 value가 null 또는 빈 문자열이 아니어야 함
|
||||||
// if (this.key === 'requiredKey') {
|
// if (this.key === 'requiredKey') {
|
||||||
// return typeof v === 'string' && v.trim().length > 0;
|
// return typeof v === 'string' && v.trim().length > 0;
|
||||||
// }
|
// }
|
||||||
// 그렇지 않은 경우 value는 null 또는 문자열, Array이어야 함
|
// 그렇지 않은 경우 value는 null 또는 문자열, Array이어야 함
|
||||||
return v === null || typeof v === 'string' || Array.isArray(v);
|
return typeof v === 'string' || Array.isArray(v);
|
||||||
},
|
},
|
||||||
message: function (props: any) {
|
message: function (props: any) {
|
||||||
if (this.key === 'requiredKey') {
|
if (this.key === 'requiredKey') {
|
||||||
return `Value is required for key "${this.key}" and cannot be null or empty.`;
|
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 },
|
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 },
|
title: { type: String, required: true },
|
||||||
order: { type: Number, required: true, default: 100 },
|
order: { type: Number, required: true, default: 100 },
|
||||||
@@ -93,17 +103,17 @@ export const TaxonomyChildItemSchema = new Schema(
|
|||||||
|
|
||||||
// **중요: 재귀 참조 설정**
|
// **중요: 재귀 참조 설정**
|
||||||
// 스키마 정의 후 .add()를 통해 자기 자신을 children 배열로 추가합니다.
|
// 스키마 정의 후 .add()를 통해 자기 자신을 children 배열로 추가합니다.
|
||||||
TaxonomyChildItemSchema.add({
|
TaxonomyChildItemSubSchema.add({
|
||||||
children: { type: [TaxonomyChildItemSchema], default: [] },
|
children: { type: [TaxonomyChildItemSubSchema], default: [] },
|
||||||
});
|
});
|
||||||
|
|
||||||
// 2. 메인 도큐먼트 스키마 (Root)
|
// 2. 메인 도큐먼트 스키마 (Root)
|
||||||
export const TaxonomySchema = new Schema(
|
export const TaxonomySchema = new Schema<Taxonomy>(
|
||||||
{
|
{
|
||||||
// items 배열은 위에서 정의한 재귀 스키마를 따름
|
// items 배열은 위에서 정의한 재귀 스키마를 따름
|
||||||
label: { type: String, required: true },
|
label: { type: String, required: true },
|
||||||
items: {
|
items: {
|
||||||
type: [TaxonomyChildItemSchema],
|
type: [TaxonomyChildItemSubSchema],
|
||||||
default: [],
|
default: [],
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -112,13 +122,35 @@ export const TaxonomySchema = new Schema(
|
|||||||
type: [MetadataSubSchema],
|
type: [MetadataSubSchema],
|
||||||
required: true,
|
required: true,
|
||||||
default: [],
|
default: [],
|
||||||
validate: {
|
validator: function (v: string | any[] | number | boolean | object | null) {
|
||||||
validator: function (metas: Metadata[]) {
|
// 'this'는 현재 검증 중인 Metadata 서브 도큐먼트를 가리킵니다.
|
||||||
const keys = metas.map((m) => m.key);
|
const dataType = (this as Metadata).dataType;
|
||||||
return keys.length === new Set(keys).size;
|
|
||||||
|
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 });
|
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 },
|
key: { type: String, required: true, unique: true },
|
||||||
label: { type: String, required: true },
|
label: { type: String, required: true },
|
||||||
sections: {
|
sections: {
|
||||||
|
|
||||||
type: [
|
type: [
|
||||||
{
|
ContentSectionSubSchema
|
||||||
heading: { type: String, required: true },
|
|
||||||
taxonomies: [{ type: Schema.Types.ObjectId, ref: 'taxonomy' }],
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
default: [],
|
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 },
|
title: { type: String, required: true },
|
||||||
content: { type: String, required: true },
|
content: { type: String, required: true },
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
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 {}
|
export class GetChildItemMetadataDto {}
|
||||||
|
|
||||||
@@ -7,8 +8,19 @@ export class GetChildItemDto {
|
|||||||
@ApiProperty({ example: 'Install' })
|
@ApiProperty({ example: 'Install' })
|
||||||
title: string;
|
title: string;
|
||||||
|
|
||||||
@ApiProperty({ required: false, example: 'install' })
|
@ApiProperty({ example: 100 })
|
||||||
href?: string;
|
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)을 리스트로 가질 수 있음을 명시
|
// 재귀적으로 자기 자신(GetChildItemDto)을 리스트로 가질 수 있음을 명시
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
@@ -21,7 +33,10 @@ export class GetChildItemDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 3. 전체 응답 DTO (Root)
|
// 3. 전체 응답 DTO (Root)
|
||||||
export class GetChildResponseDto {
|
export class GetChildItemResponseDto {
|
||||||
|
@ApiProperty({ type: String })
|
||||||
|
label: string;
|
||||||
|
|
||||||
@ApiProperty({ type: [GetChildItemDto] })
|
@ApiProperty({ type: [GetChildItemDto] })
|
||||||
@Type(() => GetChildItemDto)
|
@Type(() => GetChildItemDto)
|
||||||
items: 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 { 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')
|
@Controller('taxonomies')
|
||||||
export class TaxonomyController {
|
export class TaxonomyController {
|
||||||
constructor(private readonly taxonomyService: TaxonomyService) {}
|
constructor(private readonly taxonomyService: TaxonomyService) {}
|
||||||
|
|
||||||
@Get(':id/child-items')
|
@Get(':id/child-items')
|
||||||
getChildItems(): Promise<GetChildResponseDto> {
|
@ApiOkResponse({ type: GetChildItemResponseDto })
|
||||||
return this.taxonomyService.getChildItems();
|
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 { ConnectionService } from '../global/database/connection.service';
|
||||||
import { GetChildResponseDto } from './dto/get-child-item.dto';
|
import { GetChildItemResponseDto } from './dto/get-child-item.dto';
|
||||||
import { NotFoundError } from 'rxjs';
|
import { plainToInstance } from 'class-transformer';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TaxonomyService {
|
export class TaxonomyService {
|
||||||
constructor(private readonly connectionService: ConnectionService) {}
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
|
|
||||||
public async getChildItems(): Promise<GetChildResponseDto> {
|
public async getChildItems(taxonomyId: string): Promise<GetChildItemResponseDto> {
|
||||||
const taxonomyModel =
|
const taxonomyModel =
|
||||||
await this.connectionService.getMoeumModels('taxonomy');
|
await this.connectionService.getMoeumModels('taxonomy');
|
||||||
const response = await taxonomyModel.findOne().lean();
|
const document = await taxonomyModel.findOne({
|
||||||
if (!response) {
|
_id: taxonomyId,
|
||||||
throw new NotFoundError('No taxonomy found');
|
}, {
|
||||||
|
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